{"title": "Python/C API Reference Manual", "text": "node1.html\nnode1.html\nnode46.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n### Abstract:\nThis manual documents the API used by C (or C++) programmers who\nwant to write extension modules or embed Python. It is a companion to\nExtending and Embedding the Python Interpreter, which describes\nthe general principles of extension writing but does not document the\nAPI 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.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Introduction (node2.html#SECTION002000000000000000000)\n- 1.1 Include Files (node3.html#SECTION002100000000000000000)\n1.2 Objects, Types and Reference Counts (node4.html#SECTION002200000000000000000)\n- Reference Counts (node5.html#SECTION002210000000000000000)\nTypes (node7.html#SECTION002220000000000000000)\n1.3 Exceptions (node8.html#SECTION002300000000000000000)\n1.4 Embedding Python (node9.html#SECTION002400000000000000000)\n2 The Very High Level Layer (node10.html#SECTION003000000000000000000)\n3 Reference Counting (node11.html#SECTION004000000000000000000)\n4 Exception Handling (node12.html#SECTION005000000000000000000)\n- 4.1 Standard Exceptions (node13.html#SECTION005100000000000000000)\n5 Utilities (node14.html#SECTION006000000000000000000)\n- 5.1 OS Utilities (node15.html#SECTION006100000000000000000)\n5.2 Process Control (node16.html#SECTION006200000000000000000)\n5.3 Importing Modules (node17.html#SECTION006300000000000000000)\n6 Abstract Objects Layer (node18.html#SECTION007000000000000000000)\n- 6.1 Object Protocol (node19.html#SECTION007100000000000000000)\n6.2 Number Protocol (node20.html#SECTION007200000000000000000)\n6.3 Sequence Protocol (node21.html#SECTION007300000000000000000)\n6.4 Mapping Protocol (node22.html#SECTION007400000000000000000)\n6.5 Constructors (node23.html#SECTION007500000000000000000)\n7 Concrete Objects Layer (node24.html#SECTION008000000000000000000)\n- 7.1 Fundamental Objects (node25.html#SECTION008100000000000000000)\n- Type Objects (node26.html#SECTION008110000000000000000)\nThe None Object (node27.html#SECTION008120000000000000000)\n7.2 Sequence Objects (node28.html#SECTION008200000000000000000)\n- String Objects (node29.html#SECTION008210000000000000000)\nTuple Objects (node30.html#SECTION008220000000000000000)\nList Objects (node31.html#SECTION008230000000000000000)\n7.3 Mapping Objects (node32.html#SECTION008300000000000000000)\n- Dictionary Objects (node33.html#SECTION008310000000000000000)\n7.4 Numeric Objects (node34.html#SECTION008400000000000000000)\n- Plain Integer Objects (node35.html#SECTION008410000000000000000)\nLong Integer Objects (node36.html#SECTION008420000000000000000)\nFloating Point Objects (node37.html#SECTION008430000000000000000)\nComplex Number Objects (node38.html#SECTION008440000000000000000)\n7.5 Other Objects (node39.html#SECTION008500000000000000000)\n- File Objects (node40.html#SECTION008510000000000000000)\nCObjects (node41.html#SECTION008520000000000000000)\n8 Initialization, Finalization, and Threads (node42.html#SECTION009000000000000000000)\n- 8.1 Thread State and the Global Interpreter Lock (node43.html#SECTION009100000000000000000)\n9 Defining New Object Types (node44.html#SECTION0010000000000000000000)\n10 Debugging (node45.html#SECTION0011000000000000000000)\nIndex (node46.html#SECTION0012000000000000000000)\nAbout this document ... (node47.html#SECTION0013000000000000000000)\n---\nnode1.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 4952, "url": "https://docs.python.org/1.5/api/api.html"} {"title": "Python/C API Reference Manual", "text": "node1.html\nnode1.html\nnode46.html\n---\n# Python/C API Reference Manual\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n### Abstract:\nThis manual documents the API used by C (or C++) programmers who\nwant to write extension modules or embed Python. It is a companion to\nExtending and Embedding the Python Interpreter, which describes\nthe general principles of extension writing but does not document the\nAPI 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.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Introduction (node2.html#SECTION002000000000000000000)\n- 1.1 Include Files (node3.html#SECTION002100000000000000000)\n1.2 Objects, Types and Reference Counts (node4.html#SECTION002200000000000000000)\n- Reference Counts (node5.html#SECTION002210000000000000000)\nTypes (node7.html#SECTION002220000000000000000)\n1.3 Exceptions (node8.html#SECTION002300000000000000000)\n1.4 Embedding Python (node9.html#SECTION002400000000000000000)\n2 The Very High Level Layer (node10.html#SECTION003000000000000000000)\n3 Reference Counting (node11.html#SECTION004000000000000000000)\n4 Exception Handling (node12.html#SECTION005000000000000000000)\n- 4.1 Standard Exceptions (node13.html#SECTION005100000000000000000)\n5 Utilities (node14.html#SECTION006000000000000000000)\n- 5.1 OS Utilities (node15.html#SECTION006100000000000000000)\n5.2 Process Control (node16.html#SECTION006200000000000000000)\n5.3 Importing Modules (node17.html#SECTION006300000000000000000)\n6 Abstract Objects Layer (node18.html#SECTION007000000000000000000)\n- 6.1 Object Protocol (node19.html#SECTION007100000000000000000)\n6.2 Number Protocol (node20.html#SECTION007200000000000000000)\n6.3 Sequence Protocol (node21.html#SECTION007300000000000000000)\n6.4 Mapping Protocol (node22.html#SECTION007400000000000000000)\n6.5 Constructors (node23.html#SECTION007500000000000000000)\n7 Concrete Objects Layer (node24.html#SECTION008000000000000000000)\n- 7.1 Fundamental Objects (node25.html#SECTION008100000000000000000)\n- Type Objects (node26.html#SECTION008110000000000000000)\nThe None Object (node27.html#SECTION008120000000000000000)\n7.2 Sequence Objects (node28.html#SECTION008200000000000000000)\n- String Objects (node29.html#SECTION008210000000000000000)\nTuple Objects (node30.html#SECTION008220000000000000000)\nList Objects (node31.html#SECTION008230000000000000000)\n7.3 Mapping Objects (node32.html#SECTION008300000000000000000)\n- Dictionary Objects (node33.html#SECTION008310000000000000000)\n7.4 Numeric Objects (node34.html#SECTION008400000000000000000)\n- Plain Integer Objects (node35.html#SECTION008410000000000000000)\nLong Integer Objects (node36.html#SECTION008420000000000000000)\nFloating Point Objects (node37.html#SECTION008430000000000000000)\nComplex Number Objects (node38.html#SECTION008440000000000000000)\n7.5 Other Objects (node39.html#SECTION008500000000000000000)\n- File Objects (node40.html#SECTION008510000000000000000)\nCObjects (node41.html#SECTION008520000000000000000)\n8 Initialization, Finalization, and Threads (node42.html#SECTION009000000000000000000)\n- 8.1 Thread State and the Global Interpreter Lock (node43.html#SECTION009100000000000000000)\n9 Defining New Object Types (node44.html#SECTION0010000000000000000000)\n10 Debugging (node45.html#SECTION0011000000000000000000)\nIndex (node46.html#SECTION0012000000000000000000)\nAbout this document ... (node47.html#SECTION0013000000000000000000)\n---\nnode1.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 4952, "url": "https://docs.python.org/1.5/api/index.html"} {"title": "Contents", "text": "node2.html\napi.html\napi.html\nnode46.html\n---\n## Contents\n- 1 Introduction (node2.html#SECTION002000000000000000000)\n- 1.1 Include Files (node3.html#SECTION002100000000000000000)\n1.2 Objects, Types and Reference Counts (node4.html#SECTION002200000000000000000)\n- Reference Counts (node5.html#SECTION002210000000000000000)\n- Reference Count Details (node6.html#SECTION002211000000000000000)\nTypes (node7.html#SECTION002220000000000000000)\n1.3 Exceptions (node8.html#SECTION002300000000000000000)\n1.4 Embedding Python (node9.html#SECTION002400000000000000000)\n2 The Very High Level Layer (node10.html#SECTION003000000000000000000)\n3 Reference Counting (node11.html#SECTION004000000000000000000)\n4 Exception Handling (node12.html#SECTION005000000000000000000)\n- 4.1 Standard Exceptions (node13.html#SECTION005100000000000000000)\n5 Utilities (node14.html#SECTION006000000000000000000)\n- 5.1 OS Utilities (node15.html#SECTION006100000000000000000)\n5.2 Process Control (node16.html#SECTION006200000000000000000)\n5.3 Importing Modules (node17.html#SECTION006300000000000000000)\n6 Abstract Objects Layer (node18.html#SECTION007000000000000000000)\n- 6.1 Object Protocol (node19.html#SECTION007100000000000000000)\n6.2 Number Protocol (node20.html#SECTION007200000000000000000)\n6.3 Sequence Protocol (node21.html#SECTION007300000000000000000)\n6.4 Mapping Protocol (node22.html#SECTION007400000000000000000)\n6.5 Constructors (node23.html#SECTION007500000000000000000)\n7 Concrete Objects Layer (node24.html#SECTION008000000000000000000)\n- 7.1 Fundamental Objects (node25.html#SECTION008100000000000000000)\n- Type Objects (node26.html#SECTION008110000000000000000)\nThe None Object (node27.html#SECTION008120000000000000000)\n7.2 Sequence Objects (node28.html#SECTION008200000000000000000)\n- String Objects (node29.html#SECTION008210000000000000000)\nTuple Objects (node30.html#SECTION008220000000000000000)\nList Objects (node31.html#SECTION008230000000000000000)\n7.3 Mapping Objects (node32.html#SECTION008300000000000000000)\n- Dictionary Objects (node33.html#SECTION008310000000000000000)\n7.4 Numeric Objects (node34.html#SECTION008400000000000000000)\n- Plain Integer Objects (node35.html#SECTION008410000000000000000)\nLong Integer Objects (node36.html#SECTION008420000000000000000)\nFloating Point Objects (node37.html#SECTION008430000000000000000)\nComplex Number Objects (node38.html#SECTION008440000000000000000)\n7.5 Other Objects (node39.html#SECTION008500000000000000000)\n- File Objects (node40.html#SECTION008510000000000000000)\nCObjects (node41.html#SECTION008520000000000000000)\n8 Initialization, Finalization, and Threads (node42.html#SECTION009000000000000000000)\n- 8.1 Thread State and the Global Interpreter Lock (node43.html#SECTION009100000000000000000)\n9 Defining New Object Types (node44.html#SECTION0010000000000000000000)\n10 Debugging (node45.html#SECTION0011000000000000000000)\nIndex (node46.html#SECTION0012000000000000000000)\nAbout this document ... (node47.html#SECTION0013000000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 3018, "url": "https://docs.python.org/1.5/api/node1.html"} {"title": "2 The Very High Level Layer", "text": "node11.html\napi.html\nnode9.html\nnode1.html\nnode46.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.\n---\nguido@python.org", "python_version": "1.5", "length": 288, "url": "https://docs.python.org/1.5/api/node10.html"} {"title": "3 Reference Counting", "text": "node12.html\napi.html\nnode10.html\nnode1.html\nnode46.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 internal use:\n_Py_Dealloc(), _Py_ForgetReference(),\n_Py_NewReference(), as well as the global variable\n_Py_RefTotal.\nXXX Should mention Py_Malloc(), Py_Realloc(), Py_Free(),\nPyMem_Malloc(), PyMem_Realloc(), PyMem_Free(), PyMem_NEW(),\nPyMem_RESIZE(), PyMem_DEL(), PyMem_XDEL().\n---\nguido@python.org", "python_version": "1.5", "length": 512, "url": "https://docs.python.org/1.5/api/node11.html"} {"title": "4 Exception Handling", "text": "node13.html\napi.html\nnode11.html\nnode1.html\nnode46.html\n---\n# 4 Exception Handling\nThe functions 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 Unix\nerrno variable: there is a global indicator (per thread) of the\nlast error that occurred. Most functions don't clear this on success,\nbut will set it to indicate the cause of the error on failure. Most\nfunctions also return an error indicator, usually NULL if they are\nsupposed to return a pointer, or -1 if they return an integer\n(exception: the PyArg_Parse*() functions return 1 for\nsuccess and 0 for failure). When a function must fail because\nsome function it called failed, it generally doesn't set the error\nindicator; the function it called already set it.\nThe error indicator consists of three Python objects corresponding to\nthe Python variables sys.exc_type, sys.exc_value and\nsys.exc_traceback. API functions exist to interact with the\nerror indicator in various ways. There is a separate error indicator\nfor each thread.\n---\n- 4.1 Standard Exceptions (node13.html#SECTION005100000000000000000)\n---\nnode13.html\napi.html\nnode11.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 1255, "url": "https://docs.python.org/1.5/api/node12.html"} {"title": "4.1 Standard Exceptions", "text": "node14.html\nnode12.html\nnode12.html\nnode1.html\nnode46.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.\nThese have the type PyObject *; they are all either class\nobjects or string objects, depending on the use of the -X\noption to the interpreter. For completeness, here are all the\nvariables:\nPyExc_Exception,\nPyExc_StandardError,\nPyExc_ArithmeticError,\nPyExc_LookupError,\nPyExc_AssertionError,\nPyExc_AttributeError,\nPyExc_EOFError,\nPyExc_FloatingPointError,\nPyExc_IOError,\nPyExc_ImportError,\nPyExc_IndexError,\nPyExc_KeyError,\nPyExc_KeyboardInterrupt,\nPyExc_MemoryError,\nPyExc_NameError,\nPyExc_OverflowError,\nPyExc_RuntimeError,\nPyExc_SyntaxError,\nPyExc_SystemError,\nPyExc_SystemExit,\nPyExc_TypeError,\nPyExc_ValueError,\nPyExc_ZeroDivisionError.\n---\nguido@python.org", "python_version": "1.5", "length": 879, "url": "https://docs.python.org/1.5/api/node13.html"} {"title": "5 Utilities", "text": "node15.html\napi.html\nnode13.html\nnode1.html\nnode46.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.\n---\n- 5.1 OS Utilities (node15.html#SECTION006100000000000000000)\n5.2 Process Control (node16.html#SECTION006200000000000000000)\n5.3 Importing Modules (node17.html#SECTION006300000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 430, "url": "https://docs.python.org/1.5/api/node14.html"} {"title": "5.1 OS Utilities", "text": "node16.html\nnode14.html\nnode14.html\nnode1.html\nnode46.html\n---\n# 5.1 OS Utilities\n---\nguido@python.org", "python_version": "1.5", "length": 102, "url": "https://docs.python.org/1.5/api/node15.html"} {"title": "5.2 Process Control", "text": "node17.html\nnode14.html\nnode15.html\nnode1.html\nnode46.html\n---\n# 5.2 Process Control\n---\nguido@python.org", "python_version": "1.5", "length": 105, "url": "https://docs.python.org/1.5/api/node16.html"} {"title": "5.3 Importing Modules", "text": "node18.html\nnode14.html\nnode16.html\nnode1.html\nnode46.html\n---\n# 5.3 Importing Modules\n---\nnode18.html\nnode14.html\nnode16.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 166, "url": "https://docs.python.org/1.5/api/node17.html"} {"title": "6 Abstract Objects Layer", "text": "node19.html\napi.html\nnode17.html\nnode1.html\nnode46.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 flag a Python exception.\n---\n- 6.1 Object Protocol (node19.html#SECTION007100000000000000000)\n6.2 Number Protocol (node20.html#SECTION007200000000000000000)\n6.3 Sequence Protocol (node21.html#SECTION007300000000000000000)\n6.4 Mapping Protocol (node22.html#SECTION007400000000000000000)\n6.5 Constructors (node23.html#SECTION007500000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 691, "url": "https://docs.python.org/1.5/api/node18.html"} {"title": "6.1 Object Protocol", "text": "node20.html\nnode18.html\nnode18.html\nnode1.html\nnode46.html\n---\n# 6.1 Object Protocol\n---\nnode20.html\nnode18.html\nnode18.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 164, "url": "https://docs.python.org/1.5/api/node19.html"} {"title": "1 Introduction", "text": "node3.html\napi.html\nnode1.html\nnode1.html\nnode46.html\n---\n# 1 Introduction\nThe Application Programmer's Interface to Python gives C and C++\nprogrammers access to the Python interpreter at a variety of levels.\nThe API is equally usable from C++, but for brevity it is generally\nreferred to as the Python/C API. There are two fundamentally\ndifferent reasons for using the Python/C API. The first reason is\nto write extension modules for specific purposes; these are\nC modules that extend the Python interpreter. This is probably the\nmost common use. The second reason is to use Python as a component in\na larger application; this technique is generally referred to as\nembedding 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.\nPython 1.5 introduces a number of new API functions as well as some\nchanges to the build process that make embedding much simpler.\nThis manual describes the , state of affair.\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.\n---\n- 1.1 Include Files (node3.html#SECTION002100000000000000000)\n1.2 Objects, Types and Reference Counts (node4.html#SECTION002200000000000000000)\n- Reference Counts (node5.html#SECTION002210000000000000000)\n- Reference Count Details (node6.html#SECTION002211000000000000000)\nTypes (node7.html#SECTION002220000000000000000)\n1.3 Exceptions (node8.html#SECTION002300000000000000000)\n1.4 Embedding Python (node9.html#SECTION002400000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2003, "url": "https://docs.python.org/1.5/api/node2.html"} {"title": "6.2 Number Protocol", "text": "node21.html\nnode18.html\nnode19.html\nnode1.html\nnode46.html\n---\n# 6.2 Number Protocol\n---\nnode21.html\nnode18.html\nnode19.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 164, "url": "https://docs.python.org/1.5/api/node20.html"} {"title": "6.3 Sequence Protocol", "text": "node22.html\nnode18.html\nnode20.html\nnode1.html\nnode46.html\n---\n# 6.3 Sequence Protocol\n---\nnode22.html\nnode18.html\nnode20.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 166, "url": "https://docs.python.org/1.5/api/node21.html"} {"title": "6.4 Mapping Protocol", "text": "node23.html\nnode18.html\nnode21.html\nnode1.html\nnode46.html\n---\n# 6.4 Mapping Protocol\n---\nnode23.html\nnode18.html\nnode21.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 165, "url": "https://docs.python.org/1.5/api/node22.html"} {"title": "6.5 Constructors", "text": "node24.html\nnode18.html\nnode22.html\nnode1.html\nnode46.html\n---\n# 6.5 Constructors\n---\nnode24.html\nnode18.html\nnode22.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 161, "url": "https://docs.python.org/1.5/api/node23.html"} {"title": "7 Concrete Objects Layer", "text": "node25.html\napi.html\nnode23.html\nnode1.html\nnode46.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;\ne.g. to check that an object is a dictionary, use\nPyDict_Check(). The chapter is structured like the\n``family tree'' of Python object types.\n---\n- 7.1 Fundamental Objects (node25.html#SECTION008100000000000000000)\n- Type Objects (node26.html#SECTION008110000000000000000)\nThe None Object (node27.html#SECTION008120000000000000000)\n7.2 Sequence Objects (node28.html#SECTION008200000000000000000)\n- String Objects (node29.html#SECTION008210000000000000000)\nTuple Objects (node30.html#SECTION008220000000000000000)\nList Objects (node31.html#SECTION008230000000000000000)\n7.3 Mapping Objects (node32.html#SECTION008300000000000000000)\n- Dictionary Objects (node33.html#SECTION008310000000000000000)\n7.4 Numeric Objects (node34.html#SECTION008400000000000000000)\n- Plain Integer Objects (node35.html#SECTION008410000000000000000)\nLong Integer Objects (node36.html#SECTION008420000000000000000)\nFloating Point Objects (node37.html#SECTION008430000000000000000)\nComplex Number Objects (node38.html#SECTION008440000000000000000)\n7.5 Other Objects (node39.html#SECTION008500000000000000000)\n- File Objects (node40.html#SECTION008510000000000000000)\nCObjects (node41.html#SECTION008520000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1568, "url": "https://docs.python.org/1.5/api/node24.html"} {"title": "7.1 Fundamental Objects", "text": "node26.html\nnode24.html\nnode24.html\nnode1.html\nnode46.html\n---\n# 7.1 Fundamental Objects\nThis section describes Python type objects and the singleton object\nNone.\n---\n- Type Objects (node26.html#SECTION008110000000000000000)\nThe None Object (node27.html#SECTION008120000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 304, "url": "https://docs.python.org/1.5/api/node25.html"} {"title": "Type Objects", "text": "node27.html\nnode25.html\nnode25.html\nnode1.html\nnode46.html\n---\n## Type Objects\n---\nguido@python.org", "python_version": "1.5", "length": 99, "url": "https://docs.python.org/1.5/api/node26.html"} {"title": "The None Object", "text": "node28.html\nnode25.html\nnode26.html\nnode1.html\nnode46.html\n---\n## The None Object\n---\nguido@python.org", "python_version": "1.5", "length": 102, "url": "https://docs.python.org/1.5/api/node27.html"} {"title": "7.2 Sequence Objects", "text": "node29.html\nnode24.html\nnode27.html\nnode1.html\nnode46.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.\n---\n- String Objects (node29.html#SECTION008210000000000000000)\nTuple Objects (node30.html#SECTION008220000000000000000)\nList Objects (node31.html#SECTION008230000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 468, "url": "https://docs.python.org/1.5/api/node28.html"} {"title": "String Objects", "text": "node30.html\nnode28.html\nnode28.html\nnode1.html\nnode46.html\n---\n## String Objects\n---\nguido@python.org", "python_version": "1.5", "length": 101, "url": "https://docs.python.org/1.5/api/node29.html"} {"title": "1.1 Include Files", "text": "node4.html\nnode2.html\nnode2.html\nnode1.html\nnode46.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#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\nonly. Structure 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.\n---\nguido@python.org", "python_version": "1.5", "length": 875, "url": "https://docs.python.org/1.5/api/node3.html"} {"title": "Tuple Objects", "text": "node31.html\nnode28.html\nnode29.html\nnode1.html\nnode46.html\n---\n## Tuple Objects\n---\nnode31.html\nnode28.html\nnode29.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 159, "url": "https://docs.python.org/1.5/api/node30.html"} {"title": "List Objects", "text": "node32.html\nnode28.html\nnode30.html\nnode1.html\nnode46.html\n---\n## List Objects\n---\nguido@python.org", "python_version": "1.5", "length": 99, "url": "https://docs.python.org/1.5/api/node31.html"} {"title": "7.3 Mapping Objects", "text": "node33.html\nnode24.html\nnode31.html\nnode1.html\nnode46.html\n---\n# 7.3 Mapping Objects\n---\n- Dictionary Objects (node33.html#SECTION008310000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 173, "url": "https://docs.python.org/1.5/api/node32.html"} {"title": "Dictionary Objects", "text": "node34.html\nnode32.html\nnode32.html\nnode1.html\nnode46.html\n---\n## Dictionary Objects\n---\nnode34.html\nnode32.html\nnode32.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 164, "url": "https://docs.python.org/1.5/api/node33.html"} {"title": "7.4 Numeric Objects", "text": "node35.html\nnode24.html\nnode33.html\nnode1.html\nnode46.html\n---\n# 7.4 Numeric Objects\n---\n- Plain Integer Objects (node35.html#SECTION008410000000000000000)\nLong Integer Objects (node36.html#SECTION008420000000000000000)\nFloating Point Objects (node37.html#SECTION008430000000000000000)\nComplex Number Objects (node38.html#SECTION008440000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 372, "url": "https://docs.python.org/1.5/api/node34.html"} {"title": "Plain Integer Objects", "text": "node36.html\nnode34.html\nnode34.html\nnode1.html\nnode46.html\n---\n## Plain Integer Objects\n---\nguido@python.org", "python_version": "1.5", "length": 108, "url": "https://docs.python.org/1.5/api/node35.html"} {"title": "Long Integer Objects", "text": "node37.html\nnode34.html\nnode35.html\nnode1.html\nnode46.html\n---\n## Long Integer Objects\n---\nguido@python.org", "python_version": "1.5", "length": 107, "url": "https://docs.python.org/1.5/api/node36.html"} {"title": "Floating Point Objects", "text": "node38.html\nnode34.html\nnode36.html\nnode1.html\nnode46.html\n---\n## Floating Point Objects\n---\nguido@python.org", "python_version": "1.5", "length": 109, "url": "https://docs.python.org/1.5/api/node37.html"} {"title": "Complex Number Objects", "text": "node39.html\nnode34.html\nnode37.html\nnode1.html\nnode46.html\n---\n## Complex Number Objects\n---\nguido@python.org", "python_version": "1.5", "length": 109, "url": "https://docs.python.org/1.5/api/node38.html"} {"title": "7.5 Other Objects", "text": "node40.html\nnode24.html\nnode38.html\nnode1.html\nnode46.html\n---\n# 7.5 Other Objects\n---\n- File Objects (node40.html#SECTION008510000000000000000)\nCObjects (node41.html#SECTION008520000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 217, "url": "https://docs.python.org/1.5/api/node39.html"} {"title": "1.2 Objects, Types and Reference Counts", "text": "node5.html\nnode2.html\nnode3.html\nnode1.html\nnode46.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. All Python objects live on the heap:\nyou never declare an automatic or static variable of type\nPyObject, only pointer variables of type PyObject * can\nbe declared.\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 Reference Manual). For\neach of the well-known types there is a macro to check whether an\nobject is of that type; for instance, `PyList_Check(a)' is\ntrue iff the object pointed to by a is a Python list.\n---\n- Reference Counts (node5.html#SECTION002210000000000000000)\n- Reference Count Details (node6.html#SECTION002211000000000000000)\nTypes (node7.html#SECTION002220000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1314, "url": "https://docs.python.org/1.5/api/node4.html"} {"title": "File Objects", "text": "node41.html\nnode39.html\nnode39.html\nnode1.html\nnode46.html\n---\n## File Objects\n---\nguido@python.org", "python_version": "1.5", "length": 99, "url": "https://docs.python.org/1.5/api/node40.html"} {"title": "CObjects", "text": "node42.html\nnode39.html\nnode40.html\nnode1.html\nnode46.html\n---\n## CObjects\nXXX\n---\nguido@python.org", "python_version": "1.5", "length": 99, "url": "https://docs.python.org/1.5/api/node41.html"} {"title": "8 Initialization, Finalization, and Threads", "text": "node43.html\napi.html\nnode41.html\nnode1.html\nnode46.html\n---\n# 8 Initialization, Finalization, and Threads\n---\n- 8.1 Thread State and the Global Interpreter Lock (node43.html#SECTION009100000000000000000)\n---\nnode43.html\napi.html\nnode41.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 280, "url": "https://docs.python.org/1.5/api/node42.html"} {"title": "8.1 Thread State and the Global Interpreter Lock", "text": "node44.html\nnode42.html\nnode42.html\nnode1.html\nnode46.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 proram: 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 release 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 1.5; in earlier versions,\nsuch state was stored in global variables, and switching threads could\ncause problems. In particular, exception handling is now thread safe,\nwhen the application uses sys.exc_info() to access the\nexception last raised in the current thread.\nThere's one global variable left, however: the pointer to the current\nPyThreadState structure. While most thread packages have a way\nto store ``per-thread global data,'' Python's internal platform\nindependent thread abstraction doesn't support this yet. Therefore,\nthe current thread state must be manipulated explicitly.\nThis is easy enough in most cases. Most code manipulating the global\ninterpreter lock has the following simple structure:\n```text\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\nPy_BEGIN_ALLOW_THREADS\n...Do some blocking I/O operation...\nPy_END_ALLOW_THREADS\n```\nThe Py_BEGIN_ALLOW_THREADS macro opens a new block and declares\na hidden local variable; the 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_save = PyEval_SaveThread();\n...Do some blocking I/O operation...\nPyEval_RestoreThread(_save);\n}\n```\nUsing even lower level primitives, we can get roughly the same effect\nas follows:\n```text\n{\nPyThreadState *_save;\n_save = PyThreadState_Swap(NULL);\nPyEval_ReleaseLock();\n...Do some blocking I/O operation...\nPyEval_AcquireLock();\nPyThreadState_Swap(_save);\n}\n```\nThere are some subtle differences; in particular,\nPyEval_RestoreThread() saves and restores the value of the\nglobal variable errno, since the lock manipulation does not\nguarantee that errno is left alone. Also, when thread support\nis disabled, PyEval_SaveThread() and\nPyEval_RestoreThread() don't manipulate the lock; in this\ncase, PyEval_ReleaseLock() and\nPyEval_AcquireLock() are not available. This is done so\nthat dynamically loaded extensions compiled with thread support\nenabled can be loaded by an interpreter that was compiled with\ndisabled 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).\nXXX More?\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.\n---\nnode44.html\nnode42.html\nnode42.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 5656, "url": "https://docs.python.org/1.5/api/node43.html"} {"title": "9 Defining New Object Types", "text": "node45.html\napi.html\nnode43.html\nnode1.html\nnode46.html\n---\n# 9 Defining New Object Types\nPyObject, PyVarObject\nPyObject_HEAD, PyObject_HEAD_INIT, PyObject_VAR_HEAD\nTypedefs:\nunaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,\nintintargfunc, intobjargproc, intintobjargproc, objobjargproc,\ngetreadbufferproc, getwritebufferproc, getsegcountproc,\ndestructor, printfunc, getattrfunc, getattrofunc, setattrfunc,\nsetattrofunc, cmpfunc, reprfunc, hashfunc\nPyNumberMethods\nPySequenceMethods\nPyMappingMethods\nPyBufferProcs\nPyTypeObject\nDL_IMPORT\nPyType_Type\nPy*_Check\nPy_None, _Py_NoneStruct\n---\nguido@python.org", "python_version": "1.5", "length": 620, "url": "https://docs.python.org/1.5/api/node44.html"} {"title": "10 Debugging", "text": "node46.html\napi.html\nnode44.html\nnode1.html\nnode46.html\n---\n# 10 Debugging\nXXX Explain Py_DEBUG, Py_TRACE_REFS, Py_REF_DEBUG.\n---\nguido@python.org", "python_version": "1.5", "length": 146, "url": "https://docs.python.org/1.5/api/node45.html"} {"title": "Index", "text": "node47.html\napi.html\nnode45.html\nnode1.html\n---\n## Index\n---\nguido@python.org", "python_version": "1.5", "length": 77, "url": "https://docs.python.org/1.5/api/node46.html"} {"title": "About this document ...", "text": "api.html\nnode46.html\nnode1.html\nnode46.html\n---\n# About this document ...\nPython/C API Reference Manual\nThis document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.\nThe command line arguments were:\nlatex2html -address guido@python.org api.tex.\nThe translation was initiated by Fred L. Drake on Tue Feb 17 10:32:21 EST 1998\n---\nguido@python.org", "python_version": "1.5", "length": 581, "url": "https://docs.python.org/1.5/api/node47.html"} {"title": "Reference Counts", "text": "node6.html\nnode4.html\nnode4.html\nnode1.html\nnode46.html\n---\n## Reference Counts\nThe reference count is important because today's computers have a\nfinite (and often severly 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 increment an object's\nreference count by one, and Py_DECREF() to decrement it by\none. The decref macro is considerably more complex than the incref one,\nsince it must check whether the reference count becomes zero and then\ncause the object's deallocator, which is a function pointer contained\nin the object's type structure. The type-specific deallocator takes\ncare of decrementing the reference counts for other objects contained\nin the object, and so on, if this is a compound object type such as a\nlist. There's no chance that the reference count can overflow; at\nleast as many bits are used to hold the reference count as there are\ndistinct memory locations in virtual memory (assuming\nsizeof(long) >= sizeof(char *)). Thus, the reference count\nincrement 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 Py_DECREF()\nwhen they are done with the result; this soon becomes second nature.\n---\n- Reference Count Details (node6.html#SECTION002211000000000000000)\n---\nnode6.html\nnode4.html\nnode4.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 3628, "url": "https://docs.python.org/1.5/api/node5.html"} {"title": "Reference Count Details", "text": "node7.html\nnode5.html\nnode5.html\nnode1.html\nnode46.html\n---\n### Reference Count Details\nThe reference count behavior of functions in the Python/C API is best\nexpelained 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 PyTuple_SetItem(), which\nsteal a reference to the item (but not to the tuple or list into which\nthe item it 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 anyway):\n```text\nPyObject *t;\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\nPyObject *l, *x;\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\nPyObject *t, *l;\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\nint set_all(PyObject *target, PyObject *item)\n{\nint i, 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(), once using\nPySequence_GetItem().\n```text\nlong sum_list(PyObject *list)\n{\nint i, n;\nlong total = 0;\nPyObject *item;\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\nlong sum_sequence(PyObject *sequence)\n{\nint i, n;\nlong total = 0;\nPyObject *item;\nn = PyObject_Size(list);\nif (n < 0)\nreturn -1; /* Has no length */\nfor (i = 0; i < n; i++) {\nitem = PySequence_GetItem(list, 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```\n---\nnode7.html\nnode5.html\nnode5.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 5626, "url": "https://docs.python.org/1.5/api/node6.html"} {"title": "Types", "text": "node8.html\nnode4.html\nnode6.html\nnode1.html\nnode46.html\n---\n## 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. These will\nbe discussed together with the functions that use them.\n---\nguido@python.org", "python_version": "1.5", "length": 449, "url": "https://docs.python.org/1.5/api/node7.html"} {"title": "1.3 Exceptions", "text": "node9.html\nnode2.html\nnode7.html\nnode1.html\nnode46.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, till\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 on 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 common (though not the most\ngeneral) function to set the exception state, and\nPyErr_Clear() clears the exception 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\nobject sys.exc_type, sys.exc_value,\nsys.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 interpreter, which\ntakes care of transferring it to sys.exc_type and friends.\n(Note 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 returns 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 above. It so happens that\nthat example doesn't need to clean up any owned references when it\ndetects an error. The following example function shows some error\ncleanup. First, to remind you why you like Python, we show the\nequivalent Python code:\n```text\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\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 PyErr_Clear() to\nhandle specific exceptions, and the use of Py_XDECREF() to\ndispose of owned references that may be NULL (note the `X' in\nthe name; Py_DECREF() would crash when confronted with a\nNULL reference). It is important that the variables used to hold\nowned references are initialized to NULL for this to work;\nlikewise, the proposed return value is initialized to -1\n(failure) and only set to success after the final call made is\nsuccessful.\n---\nnode9.html\nnode2.html\nnode7.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 5488, "url": "https://docs.python.org/1.5/api/node8.html"} {"title": "1.4 Embedding Python", "text": "node10.html\nnode2.html\nnode8.html\nnode1.html\nnode46.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 Py_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\nPySys_SetArgv(argc, argv) subsequent to the call\nto Py_Initialize().\nOn most systems (in particular, on Unix and Windows, although the\ndetails are slightly different), Py_Initialize()\ncalculates the module search path based upon its best guess for the\nlocation of the standard Python interpreter executable, assuming that\nthe Python library is found in a fixed location relative to the Python\ninterpreter executable. In particular, it looks for a directory named\n`lib/python,' (replacing `,' 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/python,'. (In fact, this particular path\nis also the ``fallback'' location, used when no executable file named\n`python' 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\nPy_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 Py_GetPath(),\nPy_GetPrefix(), Py_GetExecPrefix(),\nPy_GetProgramFullPath() (all defined in\n`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 true iff Python is currently in the\ninitialized state. More information about these functions is given in\na later chapter.\n---\nnode10.html\nnode2.html\nnode8.html\nnode1.html\nnode46.html\nguido@python.org", "python_version": "1.5", "length": 2877, "url": "https://docs.python.org/1.5/api/node9.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "node1.html\nnode1.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\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 Python Tutorial. The Python\nReference Manual gives a more formal definition of the language. The\nPython Library Reference documents the existing object types,\nfunctions and modules (both built-in and written in Python) that give\nthe language its wide application range.\nFor a detailed description of the whole Python/C API, see the separate\nPython/C API Reference Manual. Note: While that manual is\nstill in a state of flux, it is safe to say that it is much more up to\ndate than the manual you're reading currently (which has been in need\nfor an upgrade for some time now).\n---\n- Contents (node1.html#SECTION001000000000000000000)\nExtending Python with C or C++ code (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 A Simple Example (node4.html#SECTION002200000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION002300000000000000000)\n1.4 Back to the Example (node6.html#SECTION002400000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION002500000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION002600000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION002700000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION002800000000000000000)\nKeyword Parsing with PyArg_ParseTupleAndKeywords() (node11.html#SECTION002900000000000000000)\nThe Py_BuildValue() Function (node12.html#SECTION0021000000000000000000)\n1.11 Reference Counts (node13.html#SECTION0021100000000000000000)\n- Introduction (node14.html#SECTION0021110000000000000000)\nReference Counting in Python (node15.html#SECTION0021120000000000000000)\nOwnership Rules (node16.html#SECTION0021130000000000000000)\nThin Ice (node17.html#SECTION0021140000000000000000)\nNULL Pointers (node18.html#SECTION0021150000000000000000)\nWriting Extensions in C++ (node19.html#SECTION0021200000000000000000)\n2 Embedding Python in another application (node20.html#SECTION003000000000000000000)\n- Embedding Python in C++ (node21.html#SECTION003100000000000000000)\n3 Dynamic Loading (node22.html#SECTION004000000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node23.html#SECTION004100000000000000000)\n- Shared Libraries (node24.html#SECTION004110000000000000000)\nSGI IRIX 4 Dynamic Loading (node25.html#SECTION004120000000000000000)\nGNU Dynamic Loading (node26.html#SECTION004130000000000000000)\n3.2 Building a Dynamically Loadable Module (node27.html#SECTION004200000000000000000)\n- Shared Libraries (node28.html#SECTION004210000000000000000)\nSGI IRIX 4 Dynamic Loading (node29.html#SECTION004220000000000000000)\nGNU Dynamic Loading (node30.html#SECTION004230000000000000000)\nAbout this document ... (node31.html#SECTION005000000000000000000)\n---\nnode1.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4962, "url": "https://docs.python.org/1.5/ext/ext.html"} {"title": "Footnotes", "text": "guido@python.org", "python_version": "1.5", "length": 16, "url": "https://docs.python.org/1.5/ext/footnode.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "node1.html\nnode1.html\n---\n# Extending and Embedding the Python Interpreter\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\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 Python Tutorial. The Python\nReference Manual gives a more formal definition of the language. The\nPython Library Reference documents the existing object types,\nfunctions and modules (both built-in and written in Python) that give\nthe language its wide application range.\nFor a detailed description of the whole Python/C API, see the separate\nPython/C API Reference Manual. Note: While that manual is\nstill in a state of flux, it is safe to say that it is much more up to\ndate than the manual you're reading currently (which has been in need\nfor an upgrade for some time now).\n---\n- Contents (node1.html#SECTION001000000000000000000)\nExtending Python with C or C++ code (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 A Simple Example (node4.html#SECTION002200000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION002300000000000000000)\n1.4 Back to the Example (node6.html#SECTION002400000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION002500000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION002600000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION002700000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION002800000000000000000)\nKeyword Parsing with PyArg_ParseTupleAndKeywords() (node11.html#SECTION002900000000000000000)\nThe Py_BuildValue() Function (node12.html#SECTION0021000000000000000000)\n1.11 Reference Counts (node13.html#SECTION0021100000000000000000)\n- Introduction (node14.html#SECTION0021110000000000000000)\nReference Counting in Python (node15.html#SECTION0021120000000000000000)\nOwnership Rules (node16.html#SECTION0021130000000000000000)\nThin Ice (node17.html#SECTION0021140000000000000000)\nNULL Pointers (node18.html#SECTION0021150000000000000000)\nWriting Extensions in C++ (node19.html#SECTION0021200000000000000000)\n2 Embedding Python in another application (node20.html#SECTION003000000000000000000)\n- Embedding Python in C++ (node21.html#SECTION003100000000000000000)\n3 Dynamic Loading (node22.html#SECTION004000000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node23.html#SECTION004100000000000000000)\n- Shared Libraries (node24.html#SECTION004110000000000000000)\nSGI IRIX 4 Dynamic Loading (node25.html#SECTION004120000000000000000)\nGNU Dynamic Loading (node26.html#SECTION004130000000000000000)\n3.2 Building a Dynamically Loadable Module (node27.html#SECTION004200000000000000000)\n- Shared Libraries (node28.html#SECTION004210000000000000000)\nSGI IRIX 4 Dynamic Loading (node29.html#SECTION004220000000000000000)\nGNU Dynamic Loading (node30.html#SECTION004230000000000000000)\nAbout this document ... (node31.html#SECTION005000000000000000000)\n---\nnode1.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4962, "url": "https://docs.python.org/1.5/ext/index.html"} {"title": "Contents", "text": "node2.html\next.html\next.html\n---\n## Contents\n- Extending Python with C or C++ code (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 A Simple Example (node4.html#SECTION002200000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION002300000000000000000)\n1.4 Back to the Example (node6.html#SECTION002400000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION002500000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION002600000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION002700000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION002800000000000000000)\nKeyword Parsing with PyArg_ParseTupleAndKeywords() (node11.html#SECTION002900000000000000000)\nThe Py_BuildValue() Function (node12.html#SECTION0021000000000000000000)\n1.11 Reference Counts (node13.html#SECTION0021100000000000000000)\n- Introduction (node14.html#SECTION0021110000000000000000)\nReference Counting in Python (node15.html#SECTION0021120000000000000000)\nOwnership Rules (node16.html#SECTION0021130000000000000000)\nThin Ice (node17.html#SECTION0021140000000000000000)\nNULL Pointers (node18.html#SECTION0021150000000000000000)\nWriting Extensions in C++ (node19.html#SECTION0021200000000000000000)\n2 Embedding Python in another application (node20.html#SECTION003000000000000000000)\n- Embedding Python in C++ (node21.html#SECTION003100000000000000000)\n3 Dynamic Loading (node22.html#SECTION004000000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node23.html#SECTION004100000000000000000)\n- Shared Libraries (node24.html#SECTION004110000000000000000)\nSGI IRIX 4 Dynamic Loading (node25.html#SECTION004120000000000000000)\nGNU Dynamic Loading (node26.html#SECTION004130000000000000000)\n3.2 Building a Dynamically Loadable Module (node27.html#SECTION004200000000000000000)\n- Shared Libraries (node28.html#SECTION004210000000000000000)\nSGI IRIX 4 Dynamic Loading (node29.html#SECTION004220000000000000000)\nGNU Dynamic Loading (node30.html#SECTION004230000000000000000)\nAbout this document ... (node31.html#SECTION005000000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2218, "url": "https://docs.python.org/1.5/ext/node1.html"} {"title": "Format Strings for PyArg_ParseTuple()", "text": "node11.html\nnode2.html\nnode9.html\nnode1.html\n---\n# Format Strings for PyArg_ParseTuple()\nThe PyArg_ParseTuple() function is declared as follows:\n```text\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 `&'\noperator to pass a variable's address.)\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 milage may vary).\nA few other characters have a meaning in a format string. These may\nnot occur inside nested parentheses. They are:\nSome example calls:\n```text\nint ok;\nint i, j;\nlong k, l;\nchar *s;\nint size;\n\nok = PyArg_ParseTuple(args, \"\"); /* No arguments */\n/* Python call: f() */\n\nok = PyArg_ParseTuple(args, \"s\", &s); /* A string */\n/* Possible Python call: f('whoops!') */\n\nok = PyArg_ParseTuple(args, \"lls\", &k, &l, &s); /* Two longs and a string */\n/* Possible Python call: f(1, 2, 'three') */\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{\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{\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{\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```\n---\nnode11.html\nnode2.html\nnode9.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3202, "url": "https://docs.python.org/1.5/ext/node10.html"} {"title": "Keyword Parsing with PyArg_ParseTupleAndKeywords()", "text": "node12.html\nnode2.html\nnode10.html\nnode1.html\n---\n# Keyword Parsing with PyArg_ParseTupleAndKeywords()\nThe PyArg_ParseTupleAndKeywords() function is declared as\nfollows:\n```text\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 a 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#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{\"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}\n```\n---\nguido@python.org", "python_version": "1.5", "length": 1833, "url": "https://docs.python.org/1.5/ext/node11.html"} {"title": "The Py_BuildValue() Function", "text": "node13.html\nnode2.html\nnode11.html\nnode1.html\n---\n# The Py_BuildValue() Function\nThis function is the counterpart to PyArg_ParseTuple(). It is\ndeclared as follows:\n```text\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), BuildValue() does\nnot always build a tuple. It builds a tuple only if its format string\ncontains two or more format units. If the format string is empty, it\nreturns None; if it contains exactly one format unit, it\nreturns whatever object is described by that format unit. To force it\nto return a tuple of size 0 or one, parenthesize 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.\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\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```\n---\nnode13.html\nnode2.html\nnode11.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2281, "url": "https://docs.python.org/1.5/ext/node12.html"} {"title": "1.11 Reference Counts", "text": "node14.html\nnode2.html\nnode12.html\nnode1.html\n---\n# 1.11 Reference Counts\n---\n- Introduction (node14.html#SECTION0021110000000000000000)\nReference Counting in Python (node15.html#SECTION0021120000000000000000)\nOwnership Rules (node16.html#SECTION0021130000000000000000)\nThin Ice (node17.html#SECTION0021140000000000000000)\nNULL Pointers (node18.html#SECTION0021150000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 401, "url": "https://docs.python.org/1.5/ext/node13.html"} {"title": "Introduction", "text": "node15.html\nnode13.html\nnode13.html\nnode1.html\n---\n## Introduction\nIn languages like C or C++, the programmer is responsible for\ndynamic allocation and deallocation of memory on the heap. In C, this\nis done using the functions malloc() and free(). In\nC++, the operators new and delete are used with\nessentially the same meaning; they are actually implemented using\nmalloc() and free(), so we'll restrict the following\ndiscussion to the latter.\nEvery block of memory allocated with malloc() should eventually\nbe returned to the pool of available memory by exactly one call to\nfree(). It is important to call free() at the right\ntime. If a block's address is forgotten but free() is not\ncalled for it, the memory it occupies cannot be reused until the\nprogram terminates. This is called a memory leak. On the other\nhand, if a program calls free() for a block and then continues\nto use the block, it creates a conflict with re-use of the block\nthrough another malloc() call. This is called using freed\nmemory. It has the same bad consequences as referencing uninitialized\ndata -- core 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 free(), it\nneeds a strategy to avoid memory leaks as well as the use of freed\nmemory. The chosen method is called reference counting. The\nprinciple is simple: every object contains a counter, which is\nincremented when a reference to the object is stored somewhere, and\nwhich is decremented when a reference to it is deleted. When the\ncounter reaches zero, the last reference to the object has been\ndeleted 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.\n---\nnode15.html\nnode13.html\nnode13.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3362, "url": "https://docs.python.org/1.5/ext/node14.html"} {"title": "Reference Counting in Python", "text": "node16.html\nnode13.html\nnode14.html\nnode1.html\n---\n## 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\nPy_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 needed.\nOwnership of a reference can be transferred. There are three ways to\ndispose of an owned reference: pass it on, store it, or call\nPy_DECREF(). Forgetting to dispose of an owned reference creates\na memory leak.\nIt is also possible to borrowfootnode.html#477 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.footnode.html#655\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).\n---\nnode16.html\nnode13.html\nnode14.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2320, "url": "https://docs.python.org/1.5/ext/node15.html"} {"title": "Ownership Rules", "text": "node17.html\nnode13.html\nnode15.html\nnode1.html\n---\n## 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() and\nPyDict_GetItem() (and PyDict_GetItemString()) all return\nreferences that you borrow from the tuple, list or dictionary.\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\nsys.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 owner.\nThere are exactly two important exceptions to this rule:\nPyTuple_SetItem() and PyList_SetItem(). These functions\ntake over ownership of the item passed to them -- even if they fail!\n(Note that PyDict_SetItem() and friends don't take over\nownership -- 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.\n---\nnode17.html\nnode13.html\nnode15.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2375, "url": "https://docs.python.org/1.5/ext/node16.html"} {"title": "Thin Ice", "text": "node18.html\nnode13.html\nnode16.html\nnode1.html\n---\n## 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 reference\nto a list item. For instance:\n```text\nbug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\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 that\nthe list passed into bug() is accessible to the\n__del__() method, it could execute a statement to the effect of\ndel 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\nno_bug(PyObject *list) {\nPyObject *item = PyList_GetItem(list, 0);\nPy_INCREF(item);\nPyList_SetItem(list, 1, PyInt_FromLong(0L));\nPyObject_Print(item, stdout, 0);\nPy_DECREF(item);\n}\n```\nThis is a true story. An older version of Python contained variants\nof this bug and someone spent a considerable amount of time in a C\ndebugger to figure out why his __del__() methods would fail...\nThe second case of problems with a borrowed reference is a variant\ninvolving threads. Normally, multiple threads in the Python\ninterpreter can't get in each other's way, because there is a global\nlock protecting Python's entire object space. However, it is possible\nto temporarily release this lock using the macro\nPy_BEGIN_ALLOW_THREADS, and to re-acquire it using\nPy_END_ALLOW_THREADS. This is common around blocking 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\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```\n---\nnode18.html\nnode13.html\nnode16.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3014, "url": "https://docs.python.org/1.5/ext/node17.html"} {"title": "NULL Pointers", "text": "node19.html\nnode13.html\nnode17.html\nnode1.html\n---\n## NULL Pointers\nIn general, functions that take object references as arguments don't\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.\\\nwhen a pointer 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()\ndon't check for NULL pointers -- however, their variants\nPy_XINCREF() and Py_XDECREF() do.\nThe macros for checking for a particular object type\n(Pytype_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.footnode.html#538\nIt is a severe error to ever let a NULL pointer ``escape'' to\nthe Python user.\n---\nguido@python.org", "python_version": "1.5", "length": 1484, "url": "https://docs.python.org/1.5/ext/node18.html"} {"title": "Writing Extensions in C++", "text": "node20.html\nnode2.html\nnode18.html\nnode1.html\n---\n# 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\nextern \"C\" {...} -- they use this form already if the symbol\n`__cplusplus' is defined (all recent C++ compilers define this\nsymbol).\n---\nguido@python.org", "python_version": "1.5", "length": 723, "url": "https://docs.python.org/1.5/ext/node19.html"} {"title": "Extending Python with C or C++ code", "text": "node3.html\next.html\nnode1.html\nnode1.html\n---\n# Extending Python with C or C++ code\n---\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 A Simple Example (node4.html#SECTION002200000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION002300000000000000000)\n1.4 Back to the Example (node6.html#SECTION002400000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION002500000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION002600000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION002700000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION002800000000000000000)\nKeyword Parsing with PyArg_ParseTupleAndKeywords() (node11.html#SECTION002900000000000000000)\nThe Py_BuildValue() Function (node12.html#SECTION0021000000000000000000)\n1.11 Reference Counts (node13.html#SECTION0021100000000000000000)\n- Introduction (node14.html#SECTION0021110000000000000000)\nReference Counting in Python (node15.html#SECTION0021120000000000000000)\nOwnership Rules (node16.html#SECTION0021130000000000000000)\nThin Ice (node17.html#SECTION0021140000000000000000)\nNULL Pointers (node18.html#SECTION0021150000000000000000)\nWriting Extensions in C++ (node19.html#SECTION0021200000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1313, "url": "https://docs.python.org/1.5/ext/node2.html"} {"title": "2 Embedding Python in another application", "text": "node21.html\next.html\nnode19.html\nnode1.html\n---\n# 2 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(). There are optional calls to pass command\nline arguments to Python. Then later you can call the interpreter\nfrom any part of the application.\nThere are several different ways to call the interpreter: you can pass\na string containing Python statements to PyRun_SimpleString(),\nor you can pass a stdio file pointer and a file name (for\nidentification in error messages only) to PyRun_SimpleFile(). You\ncan also call the lower-level operations described in the previous\nchapters to construct and use Python objects.\nA simple demo of embedding Python can be found in the directory\n`Demo/embed'.\n---\n- Embedding Python in C++ (node21.html#SECTION003100000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1361, "url": "https://docs.python.org/1.5/ext/node20.html"} {"title": "Embedding Python in C++", "text": "node22.html\nnode20.html\nnode20.html\nnode1.html\n---\n# 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++.\n---\nguido@python.org", "python_version": "1.5", "length": 402, "url": "https://docs.python.org/1.5/ext/node21.html"} {"title": "3 Dynamic Loading", "text": "node23.html\next.html\nnode21.html\nnode1.html\n---\n# 3 Dynamic Loading\nOn most modern systems it is possible to configure Python to support\ndynamic loading of extension modules implemented in C. When shared\nlibraries are used dynamic loading is configured automatically;\notherwise you have to select it as a build option (see below). Once\nconfigured, dynamic loading is trivial to use: when a Python program\nexecutes import spam, the search for modules tries to find a\nfile `spammodule.o' (`spammodule.so' when using shared\nlibraries) in the module search path, and if one is found, it is\nloaded into the executing binary and executed. Once loaded, the\nmodule acts just like a built-in extension module.\nThe advantages of dynamic loading are twofold: the ``core'' Python\nbinary gets smaller, and users can extend Python with their own\nmodules implemented in C without having to build and maintain their\nown copy of the Python interpreter. There are also disadvantages:\ndynamic loading isn't available on all systems (this just means that\non some systems you have to use static loading), and dynamically\nloading a module that was compiled for a different version of Python\n(e.g. with a different representation of objects) may dump core.\n---\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node23.html#SECTION004100000000000000000)\n- Shared Libraries (node24.html#SECTION004110000000000000000)\nSGI IRIX 4 Dynamic Loading (node25.html#SECTION004120000000000000000)\nGNU Dynamic Loading (node26.html#SECTION004130000000000000000)\n3.2 Building a Dynamically Loadable Module (node27.html#SECTION004200000000000000000)\n- Shared Libraries (node28.html#SECTION004210000000000000000)\nSGI IRIX 4 Dynamic Loading (node29.html#SECTION004220000000000000000)\nGNU Dynamic Loading (node30.html#SECTION004230000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1844, "url": "https://docs.python.org/1.5/ext/node22.html"} {"title": "3.1 Configuring and Building the Interpreter for Dynamic Loading", "text": "node24.html\nnode22.html\nnode22.html\nnode1.html\n---\n# 3.1 Configuring and Building the Interpreter for Dynamic Loading\nThere are three styles of dynamic loading: one using shared libraries,\none using SGI IRIX 4 dynamic loading, and one using GNU dynamic\nloading.\n---\n- Shared Libraries (node24.html#SECTION004110000000000000000)\nSGI IRIX 4 Dynamic Loading (node25.html#SECTION004120000000000000000)\nGNU Dynamic Loading (node26.html#SECTION004130000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 481, "url": "https://docs.python.org/1.5/ext/node23.html"} {"title": "Shared Libraries", "text": "node25.html\nnode23.html\nnode23.html\nnode1.html\n---\n## Shared Libraries\nThe following systems support dynamic loading using shared libraries:\nSunOS 4; Solaris 2; SGI IRIX 5 (but not SGI IRIX 4!); and probably all\nsystems derived from SVR4, or at least those SVR4 derivatives that\nsupport shared libraries (are there any that don't?).\nYou don't need to do anything to configure dynamic loading on these\nsystems -- the `configure' detects the presence of the\n`' header file and automatically configures dynamic\nloading.\n---\nguido@python.org", "python_version": "1.5", "length": 546, "url": "https://docs.python.org/1.5/ext/node24.html"} {"title": "SGI IRIX 4 Dynamic Loading", "text": "node26.html\nnode23.html\nnode24.html\nnode1.html\n---\n## SGI IRIX 4 Dynamic Loading\nOnly SGI IRIX 4 supports dynamic loading of modules using SGI dynamic\nloading. (SGI IRIX 5 might also support it but it is inferior to\nusing shared libraries so there is no reason to; a small test didn't\nwork right away so I gave up trying to support it.)\nBefore you build Python, you first need to fetch and build the dl\npackage written by Jack Jansen. This is available by anonymous ftp\nfrom ftp://ftp.cwi.nl/pub/dynload, file\n`dl-1.6.tar.Z'. (The version number may change.) Follow the\ninstructions in the package's `README' file to build it.\nOnce you have built dl, you can configure Python to use it. To\nthis end, you run the `configure' script with the option\n-with-dl=directory where directory is the absolute\npathname of the dl directory.\nNow build and install Python as you normally would (see the\n`README' file in the toplevel Python directory.)\n---\nguido@python.org", "python_version": "1.5", "length": 957, "url": "https://docs.python.org/1.5/ext/node25.html"} {"title": "GNU Dynamic Loading", "text": "node27.html\nnode23.html\nnode25.html\nnode1.html\n---\n## GNU Dynamic Loading\nGNU dynamic loading supports (according to its `README' file) the\nfollowing hardware and software combinations: VAX (Ultrix), Sun 3\n(SunOS 3.4 and 4.0), Sparc (SunOS 4.0), Sequent Symmetry (Dynix), and\nAtari ST. There is no reason to use it on a Sparc; I haven't seen a\nSun 3 for years so I don't know if these have shared libraries or not.\nYou need to fetch and build two packages.\nOne is GNU DLD. All development of this code has been done with DLD\nversion 3.2.3, which is available by anonymous ftp from\nftp://ftp.cwi.nl/pub/dynload, file\n`dld-3.2.3.tar.Z'. (A more recent version of DLD is available\nvia http://www-swiss.ai.mit.edu/ jaffer/DLD.html but this has\nnot been tested.)\nThe other package needed is an\nemulation of Jack Jansen's dl package that I wrote on top of\nGNU DLD 3.2.3. This is available from the same host and directory,\nfile `dl-dld-1.1.tar.Z'. (The version number may change -- but I doubt\nit will.) Follow the instructions in each package's `README'\nfile to configure and build them.\nNow configure Python. Run the `configure' script with the option\n-with-dl-dld=dl-directory,dld-directory where\ndl-directory is the absolute pathname of the directory where you\nhave built the `dl-dld' package, and dld-directory is that\nof the GNU DLD package. The Python interpreter you build hereafter\nwill support GNU dynamic loading.\n---\nguido@python.org", "python_version": "1.5", "length": 1439, "url": "https://docs.python.org/1.5/ext/node26.html"} {"title": "3.2 Building a Dynamically Loadable Module", "text": "node28.html\nnode22.html\nnode26.html\nnode1.html\n---\n# 3.2 Building a Dynamically Loadable Module\nSince there are three styles of dynamic loading, there are also three\ngroups of instructions for building a dynamically loadable module.\nInstructions common for all three styles are given first. Assuming\nyour module is called spam, the source filename must be\n`spammodule.c', so the object name is `spammodule.o'. The\nmodule must be written as a normal Python extension module (as\ndescribed earlier).\nNote that in all cases you will have to create your own Makefile that\ncompiles your module file(s). This Makefile will have to pass two\n`-I' arguments to the C compiler which will make it find the\nPython header files. If the Make variable PYTHONTOP points to\nthe toplevel Python directory, your CFLAGS Make variable should\ncontain the options `-I$(PYTHONTOP) -I$(PYTHONTOP)/Include'.\n(Most header files are in the `Include' subdirectory, but the\n`config.h' header lives in the toplevel directory.)\n---\n- Shared Libraries (node28.html#SECTION004210000000000000000)\nSGI IRIX 4 Dynamic Loading (node29.html#SECTION004220000000000000000)\nGNU Dynamic Loading (node30.html#SECTION004230000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1214, "url": "https://docs.python.org/1.5/ext/node27.html"} {"title": "Shared Libraries", "text": "node29.html\nnode27.html\nnode27.html\nnode1.html\n---\n## Shared Libraries\nYou must link the `.o' file to produce a shared library. This is\ndone using a special invocation of the Unix loader/linker,\nld(1). Unfortunately the invocation differs slightly per\nsystem.\nOn SunOS 4, use\n```text\nld spammodule.o -o spammodule.so\n```\nOn Solaris 2, use\n```text\nld -G spammodule.o -o spammodule.so\n```\nOn SGI IRIX 5, use\n```text\nld -shared spammodule.o -o spammodule.so\n```\nOn other systems, consult the manual page for ld(1) to find what\nflags, if any, must be used.\nIf your extension module uses system libraries that haven't already\nbeen linked with Python (e.g. a windowing system), these must be\npassed to the ld command as `-l' options after the\n`.o' file.\nThe resulting file `spammodule.so' must be copied into a directory\nalong the Python module search path.\n---\nguido@python.org", "python_version": "1.5", "length": 872, "url": "https://docs.python.org/1.5/ext/node28.html"} {"title": "SGI IRIX 4 Dynamic Loading", "text": "node30.html\nnode27.html\nnode28.html\nnode1.html\n---\n## SGI IRIX 4 Dynamic Loading\nIMPORTANT: You must compile your extension module with the\nadditional C flag `-G0' (or `-G 0'). This instruct the\nassembler to generate position-independent code.\nYou don't need to link the resulting `spammodule.o' file; just\ncopy it into a directory along the Python module search path.\nThe first time your extension is loaded, it takes some extra time and\na few messages may be printed. This creates a file\n`spammodule.ld' which is an image that can be loaded quickly into\nthe Python interpreter process. When a new Python interpreter is\ninstalled, the dl package detects this and rebuilds\n`spammodule.ld'. The file `spammodule.ld' is placed in the\ndirectory where `spammodule.o' was found, unless this directory is\nunwritable; in that case it is placed in a temporary\ndirectory.footnode.html#661\nIf your extension modules uses additional system libraries, you must\ncreate a file `spammodule.libs' in the same directory as the\n`spammodule.o'. This file should contain one or more lines with\nwhitespace-separated options that will be passed to the linker --\nnormally only `-l' options or absolute pathnames of libraries\n(`.a' files) should be used.\n---\nguido@python.org", "python_version": "1.5", "length": 1251, "url": "https://docs.python.org/1.5/ext/node29.html"} {"title": "1.1 Introduction", "text": "node4.html\nnode2.html\nnode2.html\nnode1.html\n---\n# 1.1 Introduction\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 a later section.\n---\nguido@python.org", "python_version": "1.5", "length": 772, "url": "https://docs.python.org/1.5/ext/node3.html"} {"title": "GNU Dynamic Loading", "text": "node31.html\nnode27.html\nnode29.html\nnode1.html\n---\n## GNU Dynamic Loading\nJust copy `spammodule.o' into a directory along the Python module\nsearch path.\nIf your extension modules uses additional system libraries, you must\ncreate a file `spammodule.libs' in the same directory as the\n`spammodule.o'. This file should contain one or more lines with\nwhitespace-separated absolute pathnames of libraries (`.a'\nfiles). No `-l' options can be used.\n---\nguido@python.org", "python_version": "1.5", "length": 463, "url": "https://docs.python.org/1.5/ext/node30.html"} {"title": "About this document ...", "text": "ext.html\nnode30.html\nnode1.html\n---\n# About this document ...\nExtending and Embedding the Python Interpreter\nThis document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.\nThe command line arguments were:\nlatex2html -address guido@python.org ext.tex.\nThe translation was initiated by Fred L. Drake on Tue Feb 17 10:28:43 EST 1998\n---\nguido@python.org", "python_version": "1.5", "length": 586, "url": "https://docs.python.org/1.5/ext/node31.html"} {"title": "1.2 A Simple Example", "text": "node5.html\nnode2.html\nnode3.html\nnode1.html\n---\n# 1.2 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().footnode.html#637\nThis 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>>> import spam\n>>> status = spam.system(\"ls -l\")\n```\nBegin by creating a file `spammodule.c'. (In general, 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#include \"Python.h\"\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(), free() and\nrealloc() 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)'\nis evaluated (we'll see shortly how it ends up being called):\n```text\nstatic PyObject *\nspam_system(self, args)\nPyObject *self;\nPyObject *args;\n{\nchar *command;\nint sts;\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\nbuiltin method. This will be discussed later. In the example,\nself will always be a NULL pointer, since we are defining\na function, not a method. (This is done so that the interpreter\ndoesn't have to understand 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 by so the calling function can return\nNULL immediately (as we saw in the example).\n---\nnode5.html\nnode2.html\nnode3.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3311, "url": "https://docs.python.org/1.5/ext/node4.html"} {"title": "1.3 Intermezzo: Errors and Exceptions", "text": "node6.html\nnode2.html\nnode4.html\nnode1.html\n---\n# 1.3 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\nsys.exc_type, sys.exc_value and sys.exc_traceback\n(see the section on module sys in the Library Reference\nManual). It is important to know about them to understand how errors\nare passed around.\nThe Python API defines a number of functions to set various types of\nexceptions.\nThe most common one is PyErr_SetString(). Its arguments are an\nexception object and a C string. The exception object is usually a\npredefined object like PyExc_ZeroDivisionError. The C string\nindicates the cause of the error and is converted to a Python string\nobject and stored as the ``associated value'' of the exception.\nAnother useful function is PyErr_SetFromErrno(), which only\ntakes an exception argument and constructs the associated value by\ninspection of the (Unix) 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).\nNote that a failing malloc() call must be turned into an\nexception -- the direct caller of malloc() (or\nrealloc()) must call PyErr_NoMemory() and return a\nfailure indicator itself. All the object-creating functions\n(PyInt_FromLong() etc.) already do this, so only if you call\nmalloc() directly this note is of importance.\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 Py_XDECREF()\nor Py_DECREF() calls for objects you have already created) when\nyou 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_ZeroDevisionError 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\nwhich must 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\nstatic PyObject *SpamError;\n```\nand initialize it in your module's initialization function\n(initspam()) with a string object, e.g. (leaving out the error\nchecking for now):\n```text\nvoid\ninitspam()\n{\nPyObject *m, *d;\nm = Py_InitModule(\"spam\", SpamMethods);\nd = PyModule_GetDict(m);\nSpamError = PyString_FromString(\"spam.error\");\nPyDict_SetItemString(d, \"error\", SpamError);\n}\n```\nNote that the Python name for the exception object is\nspam.error. It is conventional for module and exception names\nto be spelled in lower case. It is also conventional that the\nvalue of the exception object is the same as its name, e.g.\\\nthe string \"spam.error\".\n---\nnode6.html\nnode2.html\nnode4.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 5449, "url": "https://docs.python.org/1.5/ext/node5.html"} {"title": "1.4 Back to the Example", "text": "node7.html\nnode2.html\nnode5.html\nnode1.html\n---\n# 1.4 Back to the Example\nGoing back to our example function, you should now be able to\nunderstand this statement:\n```text\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 system(),\npassing it the string we just got from PyArg_ParseTuple():\n```text\nsts = system(command);\n```\nOur spam.system() function must return the value of sts\nas 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 arbitrary\nnumber of C values, and returns a new Python object. More info on\nPy_BuildValue() is given later.\n```text\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\nNone. You need this idiom to do so:\n```text\nPy_INCREF(Py_None);\nreturn Py_None;\n```\nPy_None is the C name for the special Python object\nNone. It is a genuine Python object (not a NULL\npointer, which means ``error'' in most contexts, as we have seen).\n---\nguido@python.org", "python_version": "1.5", "length": 1716, "url": "https://docs.python.org/1.5/ext/node6.html"} {"title": "1.5 The Module's Method Table and Initialization Function", "text": "node8.html\nnode2.html\nnode6.html\nnode1.html\n---\n# 1.5 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\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 keyword\narguments should be passed to the function. In this case, the C\nfunction should accept a third `PyObject *' parameter which will\nbe a dictionary of keywords. Use PyArg_ParseTupleAndKeywords()\nto parse the arguemts to such a function.\nThe method table must be passed to the interpreter in the module's\ninitialization function (which should be the only non-static\nitem defined in the module file):\n```text\nvoid\ninitspam()\n{\n(void) Py_InitModule(\"spam\", SpamMethods);\n}\n```\nWhen the Python program imports module spam for the first time,\ninitspam() is called. It calls Py_InitModule(), which\ncreates a ``module object'' (which is inserted in the dictionary\nsys.modules under the key \"spam\"), and inserts built-in\nfunction objects into the newly created module based upon the table\n(an array of PyMethodDef structures) that was passed as its\nsecond argument. Py_InitModule() returns a pointer to the\nmodule object that it creates (which is unused here). It aborts with\na fatal error if the module could not be initialized satisfactorily,\nso the caller doesn't need to check for errors.\n---\nguido@python.org", "python_version": "1.5", "length": 2038, "url": "https://docs.python.org/1.5/ext/node7.html"} {"title": "1.6 Compilation and Linkage", "text": "node9.html\nnode2.html\nnode7.html\nnode1.html\n---\n# 1.6 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 chapter on Dynamic Loading for more info about\nthis.\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, add a line to the file\n`Modules/Setup' describing your file:\n```text\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 rebuilt the `Makefile'\nthere by running make Makefile. (This is necessary each time\nyou change the `Setup' file.)\nIf your module requires additional libraries to link with, these can\nbe listed on the line in the `Setup' file as well, for instance:\n```text\nspam spammodule.o -lX11\n```\n---\nguido@python.org", "python_version": "1.5", "length": 1197, "url": "https://docs.python.org/1.5/ext/node8.html"} {"title": "1.7 Calling Python Functions From C", "text": "node10.html\nnode2.html\nnode8.html\nnode1.html\n---\n# 1.7 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'.)\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 whereever you see fit.\nFor example, the following function might be part of a module\ndefinition:\n```text\nstatic PyObject *my_callback = NULL;\n\nstatic PyObject *\nmy_set_callback(dummy, arg)\nPyObject *dummy, *arg;\n{\nPy_XDECREF(my_callback); /* Dispose of previous callback */\nPy_XINCREF(arg); /* Add a reference to new callback */\nmy_callback = arg; /* Remember new callback */\n/* Boilerplate to return \"None\" */\nPy_INCREF(Py_None);\nreturn Py_None;\n}\n```\nThe macros Py_XINCREF() and Py_XDECREF() increment/decrement\nthe reference count of an object and are safe in the presence of\nNULL pointers. More info on them in the section on Reference\nCounts below.\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\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 raising\nan exception. If the C code that called PyEval_CallObject() is\ncalled from Python, it should now return an error indication to its\nPython caller, so the interpreter can print a stack trace, or the\ncalling Python code can handle the exception. If this is not possible\nor desirable, the exception should be cleared by calling\nPyErr_Clear(). For example:\n```text\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 PyEval_CallObject().\nIn some cases the argument list is also provided by the Python\nprogram, through the same interface that specified the callback\nfunction. It can then be saved and used in the same manner as the\nfunction object. In other cases, you may have to construct a new\ntuple to pass as the argument list. The simplest way to do this is to\ncall Py_BuildValue(). For example, if you want to pass an integral\nevent code, you might use the following code:\n```text\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(argument) immediately after the call,\nbefore the error check! Also note that strictly spoken this code is\nnot complete: Py_BuildValue() may run out of memory, and this should\nbe checked.\n---\nnode10.html\nnode2.html\nnode8.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4952, "url": "https://docs.python.org/1.5/ext/node9.html"} {"title": "Python 1.5 Documentation", "text": "# Python 1.5 Documentation\n- Tutorial (tut/tut.html) (start here)\n Library Reference (lib/lib.html) (keep this under your pillow)\n Language Reference (ref/ref-1.html) (for language lawyers)\n Extending and Embedding (ext/ext.html) (tutorial for\n C/C++ programmers)\n Python/C API (api/api.html) (reference for C/C++\n programmers)", "python_version": "1.5", "length": 333, "url": "https://docs.python.org/1.5/index.html"} {"title": "Footnotes", "text": "guido@python.org", "python_version": "1.5", "length": 16, "url": "https://docs.python.org/1.5/lib/footnode.html"} {"title": "Python Library Reference", "text": "node1.html\nnode1.html\nnode270.html\n---\n# Python Library Reference\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE 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 describes the exact syntax and\nsemantics of the language, it does not describe the standard library\nthat is distributed with the language, and which greatly enhances its\nimmediate usability. This library contains built-in modules (written\nin C) that provide access to system functionality such as file I/O\nthat would otherwise be inaccessible to Python programmers, as well as\nmodules written in Python that provide standardized solutions for many\nproblems that occur in everyday programming. Some of these modules\nare explicitly designed to encourage and enhance the portability of\nPython 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 Python Tutorial; the\nPython Reference Manual remains the highest authority on\nsyntactic and semantic questions. Finally, the manual entitled\nExtending and Embedding the Python Interpreter describes how to\nadd new extensions to Python and how to embed it in other applications.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Introduction (node2.html#SECTION002000000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION003000000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION003100000000000000000)\n- Truth Value Testing (node5.html#SECTION003110000000000000000)\nBoolean Operations (node6.html#SECTION003120000000000000000)\nComparisons (node7.html#SECTION003130000000000000000)\nNumeric Types (node8.html#SECTION003140000000000000000)\nSequence Types (node10.html#SECTION003150000000000000000)\nMapping Types (node13.html#SECTION003160000000000000000)\nOther Built-in Types (node14.html#SECTION003170000000000000000)\nSpecial Attributes (node24.html#SECTION003180000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION003200000000000000000)\n2.3 Built-in Functions (node26.html#SECTION003300000000000000000)\n3 Python Services (node27.html#SECTION004000000000000000000)\n- 3.1 Built-in Module sys (node28.html#SECTION004100000000000000000)\n3.2 Standard Module types (node29.html#SECTION004200000000000000000)\n3.3 Standard Modules UserDict and UserList (node30.html#SECTION004300000000000000000)\n3.4 Built-in Module operator (node31.html#SECTION004400000000000000000)\n3.5 Standard Module traceback (node32.html#SECTION004500000000000000000)\n3.6 Standard Module pickle (node33.html#SECTION004600000000000000000)\nStandard Module copy_reg (node34.html#SECTION004700000000000000000)\n3.8 Standard Module shelve (node35.html#SECTION004800000000000000000)\n3.9 Standard Module copy (node36.html#SECTION004900000000000000000)\n3.10 Built-in Module marshal (node37.html#SECTION0041000000000000000000)\n3.11 Built-in Module imp (node38.html#SECTION0041100000000000000000)\n- Examples (node39.html#SECTION0041110000000000000000)\n3.12 Standard Module ni (node40.html#SECTION0041200000000000000000)\n3.13 Built-in Module parser (node41.html#SECTION0041300000000000000000)\n- Creating AST Objects (node42.html#SECTION0041310000000000000000)\nConverting AST Objects (node43.html#SECTION0041320000000000000000)\nQueries on AST Objects (node44.html#SECTION0041330000000000000000)\nExceptions and Error Handling (node45.html#SECTION0041340000000000000000)\nAST Objects (node46.html#SECTION0041350000000000000000)\nExamples (node47.html#SECTION0041360000000000000000)\n3.14 Standard Module symbol (node50.html#SECTION0041400000000000000000)\n3.15 Standard Module token (node51.html#SECTION0041500000000000000000)\n3.16 Standard Module keyword (node52.html#SECTION0041600000000000000000)\n3.17 Standard Module code (node53.html#SECTION0041700000000000000000)\n3.18 Standard Module pprint (node54.html#SECTION0041800000000000000000)\n- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)\n3.19 Standard Module dis (node56.html#SECTION0041900000000000000000)\n- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)\n3.20 Standard Module site (node58.html#SECTION0042000000000000000000)\n3.21 Standard Module user (node59.html#SECTION0042100000000000000000)\nBuilt-in Module __builtin__ (node60.html#SECTION0042200000000000000000)\nBuilt-in Module __main__ (node61.html#SECTION0042300000000000000000)\n4 String Services (node62.html#SECTION005000000000000000000)\n- 4.1 Standard Module string (node63.html#SECTION005100000000000000000)\n4.2 Built-in Module re (node64.html#SECTION005200000000000000000)\n- Regular Expression Syntax (node65.html#SECTION005210000000000000000)\nModule Contents (node66.html#SECTION005220000000000000000)\nRegular Expression Objects (node67.html#SECTION005230000000000000000)\nMatch Objects (node68.html#SECTION005240000000000000000)\n4.3 Built-in Module regex (node69.html#SECTION005300000000000000000)\n- Regular Expressions (node70.html#SECTION005310000000000000000)\nModule Contents (node71.html#SECTION005320000000000000000)\n4.4 Standard Module regsub (node72.html#SECTION005400000000000000000)\n4.5 Built-in Module struct (node73.html#SECTION005500000000000000000)\n4.6 Standard Module StringIO (node74.html#SECTION005600000000000000000)\n4.7 Built-in Module soundex (node75.html#SECTION005700000000000000000)\n5 Miscellaneous Services (node76.html#SECTION006000000000000000000)\n- 5.1 Built-in Module math (node77.html#SECTION006100000000000000000)\n5.2 Built-in Module cmath (node78.html#SECTION006200000000000000000)\n5.3 Standard Module whrandom (node79.html#SECTION006300000000000000000)\n5.4 Standard Module random (node80.html#SECTION006400000000000000000)\n5.5 Standard Module rand (node81.html#SECTION006500000000000000000)\n5.6 Built-in Module array (node82.html#SECTION006600000000000000000)\n6 Generic Operating System Services (node83.html#SECTION007000000000000000000)\n- 6.1 Standard Module os (node84.html#SECTION007100000000000000000)\n6.2 Built-in Module time (node85.html#SECTION007200000000000000000)\n6.3 Standard Module getopt (node86.html#SECTION007300000000000000000)\n6.4 Standard Module tempfile (node87.html#SECTION007400000000000000000)\n6.5 Standard Module errno (node88.html#SECTION007500000000000000000)\n6.6 Standard Module glob (node89.html#SECTION007600000000000000000)\n6.7 Standard Module fnmatch (node90.html#SECTION007700000000000000000)\n6.8 Standard Module locale (node91.html#SECTION007800000000000000000)\n7 Optional Operating System Services (node92.html#SECTION008000000000000000000)\n- 7.1 Built-in Module signal (node93.html#SECTION008100000000000000000)\n7.2 Built-in Module socket (node94.html#SECTION008200000000000000000)\n- Socket Objects (node95.html#SECTION008210000000000000000)\nExample (node96.html#SECTION008220000000000000000)\n7.3 Built-in Module select (node97.html#SECTION008300000000000000000)\n7.4 Built-in Module thread (node98.html#SECTION008400000000000000000)\n7.5 Standard Module Queue (node99.html#SECTION008500000000000000000)\n- Queue Objects (node100.html#SECTION008510000000000000000)\n7.6 Standard Modules anydbm and dumbdbm (node101.html#SECTION008600000000000000000)\n7.7 Standard Module whichdb (node102.html#SECTION008700000000000000000)\n7.8 Built-in Module zlib (node103.html#SECTION008800000000000000000)\n7.9 Built-in Module gzip (node104.html#SECTION008900000000000000000)\n8 Unix Specific Services (node105.html#SECTION009000000000000000000)\n- 8.1 Built-in Module posix (node106.html#SECTION009100000000000000000)\n8.2 Standard Module posixpath (node107.html#SECTION009200000000000000000)\n8.3 Built-in Module pwd (node108.html#SECTION009300000000000000000)\n8.4 Built-in Module grp (node109.html#SECTION009400000000000000000)\n8.5 Built-in Module crypt (node110.html#SECTION009500000000000000000)\n8.6 Built-in Module dbm (node111.html#SECTION009600000000000000000)\n8.7 Built-in Module gdbm (node112.html#SECTION009700000000000000000)\n8.8 Built-in Module termios (node113.html#SECTION009800000000000000000)\n- Example (node114.html#SECTION009810000000000000000)\n8.9 Standard Module TERMIOS (node115.html#SECTION009900000000000000000)\n8.10 Built-in Module fcntl (node116.html#SECTION0091000000000000000000)\n8.11 Standard Module posixfile (node117.html#SECTION0091100000000000000000)\n8.12 Built-in Module resource (node118.html#SECTION0091200000000000000000)\n- Resource Limits (node119.html#SECTION0091210000000000000000)\nResource Usage (node120.html#SECTION0091220000000000000000)\n8.13 Built-in Module syslog (node121.html#SECTION0091300000000000000000)\n8.14 Standard Module stat (node122.html#SECTION0091400000000000000000)\n8.15 Standard Module commands (node123.html#SECTION0091500000000000000000)\n9 The Python Debugger (node124.html#SECTION0010000000000000000000)\n- 9.1 Debugger Commands (node125.html#SECTION0010100000000000000000)\n9.2 How It Works (node126.html#SECTION0010200000000000000000)\n10 The Python Profiler (node127.html#SECTION0011000000000000000000)\n- 10.1 Introduction to the profiler (node128.html#SECTION0011100000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node129.html#SECTION0011200000000000000000)\n10.3 Instant Users Manual (node130.html#SECTION0011300000000000000000)\n10.4 What Is Deterministic Profiling? (node131.html#SECTION0011400000000000000000)\n10.5 Reference Manual (node132.html#SECTION0011500000000000000000)\n- The Stats Class (node133.html#SECTION0011510000000000000000)\n10.6 Limitations (node134.html#SECTION0011600000000000000000)\n10.7 Calibration (node135.html#SECTION0011700000000000000000)\n10.8 Extensions - Deriving Better Profilers (node136.html#SECTION0011800000000000000000)\n- OldProfile Class (node137.html#SECTION0011810000000000000000)\nHotProfile Class (node138.html#SECTION0011820000000000000000)\n11 Internet and WWW Services (node139.html#SECTION0012000000000000000000)\n- 11.1 Standard Module cgi (node140.html#SECTION0012100000000000000000)\n- Introduction (node141.html#SECTION0012110000000000000000)\nUsing the cgi module (node142.html#SECTION0012120000000000000000)\nOld classes (node143.html#SECTION0012130000000000000000)\nFunctions (node144.html#SECTION0012140000000000000000)\nCaring about security (node145.html#SECTION0012150000000000000000)\nInstalling your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)\nTesting your CGI script (node147.html#SECTION0012170000000000000000)\nDebugging CGI scripts (node148.html#SECTION0012180000000000000000)\nCommon problems and solutions (node149.html#SECTION0012190000000000000000)\n11.2 Standard Module urllib (node150.html#SECTION0012200000000000000000)\n11.3 Standard Module httplib (node151.html#SECTION0012300000000000000000)\n- HTTP Objects (node152.html#SECTION0012310000000000000000)\nExample (node153.html#SECTION0012320000000000000000)\n11.4 Standard Module ftplib (node154.html#SECTION0012400000000000000000)\n- FTP Objects (node155.html#SECTION0012410000000000000000)\n11.5 Standard Module gopherlib (node156.html#SECTION0012500000000000000000)\n11.6 Standard Module nntplib (node157.html#SECTION0012600000000000000000)\n- NNTP Objects (node158.html#SECTION0012610000000000000000)\n11.7 Standard Module urlparse (node159.html#SECTION0012700000000000000000)\n11.8 Standard Module sgmllib (node160.html#SECTION0012800000000000000000)\n11.9 Standard Module htmllib (node161.html#SECTION0012900000000000000000)\n11.10 Standard Module xmllib (node162.html#SECTION00121000000000000000000)\n11.11 Standard Module formatter (node163.html#SECTION00121100000000000000000)\n- The Formatter Interface (node164.html#SECTION00121110000000000000000)\nFormatter Implementations (node165.html#SECTION00121120000000000000000)\nThe Writer Interface (node166.html#SECTION00121130000000000000000)\nWriter Implementations (node167.html#SECTION00121140000000000000000)\n11.12 Standard Module rfc822 (node168.html#SECTION00121200000000000000000)\n- Message Objects (node169.html#SECTION00121210000000000000000)\n11.13 Standard Module mimetools (node170.html#SECTION00121300000000000000000)\n- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)\n11.14 Standard Module binhex (node172.html#SECTION00121400000000000000000)\n- Notes (node173.html#SECTION00121410000000000000000)\n11.15 Standard Module uu (node174.html#SECTION00121500000000000000000)\n11.16 Built-in Module binascii (node175.html#SECTION00121600000000000000000)\n11.17 Standard Module xdrlib (node176.html#SECTION00121700000000000000000)\n- Packer Objects (node177.html#SECTION00121710000000000000000)\nUnpacker Objects (node178.html#SECTION00121720000000000000000)\nExceptions (node179.html#SECTION00121730000000000000000)\n11.18 Standard Module mailcap (node180.html#SECTION00121800000000000000000)\n11.19 Standard Module base64 (node181.html#SECTION00121900000000000000000)\n11.20 Standard Module quopri (node182.html#SECTION00122000000000000000000)\n11.21 Standard Module SocketServer (node183.html#SECTION00122100000000000000000)\n11.22 Standard Module mailbox (node184.html#SECTION00122200000000000000000)\n- Mailbox Objects (node185.html#SECTION00122210000000000000000)\n11.23 Standard Module mimify (node186.html#SECTION00122300000000000000000)\n11.24 Standard Module BaseHTTPServer (node187.html#SECTION00122400000000000000000)\n12 Restricted Execution (node188.html#SECTION0013000000000000000000)\n- 12.1 Standard Module rexec (node189.html#SECTION0013100000000000000000)\n- An example (node190.html#SECTION0013110000000000000000)\n12.2 Standard Module Bastion (node191.html#SECTION0013200000000000000000)\n13 Multimedia Services (node192.html#SECTION0014000000000000000000)\n- 13.1 Built-in Module audioop (node193.html#SECTION0014100000000000000000)\n13.2 Built-in Module imageop (node194.html#SECTION0014200000000000000000)\n13.3 Standard Module aifc (node195.html#SECTION0014300000000000000000)\n13.4 Built-in Module jpeg (node196.html#SECTION0014400000000000000000)\n13.5 Built-in Module rgbimg (node197.html#SECTION0014500000000000000000)\n13.6 Standard Module imghdr (node198.html#SECTION0014600000000000000000)\n14 Cryptographic Services (node199.html#SECTION0015000000000000000000)\n- 14.1 Built-in Module md5 (node200.html#SECTION0015100000000000000000)\n14.2 Built-in Module mpz (node201.html#SECTION0015200000000000000000)\n14.3 Built-in Module rotor (node202.html#SECTION0015300000000000000000)\n15 Macintosh Specific Services (node203.html#SECTION0016000000000000000000)\n- 15.1 Built-in Module mac (node204.html#SECTION0016100000000000000000)\n15.2 Standard Module macpath (node205.html#SECTION0016200000000000000000)\n15.3 Built-in Module ctb (node206.html#SECTION0016300000000000000000)\n- connection object (node207.html#SECTION0016310000000000000000)\n15.4 Built-in Module macconsole (node208.html#SECTION0016400000000000000000)\n- macconsole options object (node209.html#SECTION0016410000000000000000)\nconsole window object (node210.html#SECTION0016420000000000000000)\n15.5 Built-in Module macdnr (node211.html#SECTION0016500000000000000000)\n- dnr result object (node212.html#SECTION0016510000000000000000)\n15.6 Built-in Module macfs (node213.html#SECTION0016600000000000000000)\n- FSSpec objects (node214.html#SECTION0016610000000000000000)\nalias objects (node215.html#SECTION0016620000000000000000)\nFInfo objects (node216.html#SECTION0016630000000000000000)\n15.7 Standard Module ic (node217.html#SECTION0016700000000000000000)\n- IC objects (node218.html#SECTION0016710000000000000000)\n15.8 Built-in Module MacOS (node219.html#SECTION0016800000000000000000)\n15.9 Standard Module macostools (node220.html#SECTION0016900000000000000000)\n15.10 Standard Module findertools (node221.html#SECTION00161000000000000000000)\n15.11 Built-in Module mactcp (node222.html#SECTION00161100000000000000000)\n- TCP Stream Objects (node223.html#SECTION00161110000000000000000)\nTCP Status Objects (node224.html#SECTION00161120000000000000000)\nUDP Stream Objects (node225.html#SECTION00161130000000000000000)\n15.12 Built-in Module macspeech (node226.html#SECTION00161200000000000000000)\n- voice objects (node227.html#SECTION00161210000000000000000)\nspeech channel objects (node228.html#SECTION00161220000000000000000)\n15.13 Standard Module EasyDialogs (node229.html#SECTION00161300000000000000000)\n15.14 Standard Module FrameWork (node230.html#SECTION00161400000000000000000)\n- Application objects (node231.html#SECTION00161410000000000000000)\nWindow Objects (node232.html#SECTION00161420000000000000000)\nControlsWindow Object (node233.html#SECTION00161430000000000000000)\nScrolledWindow Object (node234.html#SECTION00161440000000000000000)\nDialogWindow Objects (node235.html#SECTION00161450000000000000000)\n15.15 Standard Module MiniAEFrame (node236.html#SECTION00161500000000000000000)\n- AEServer Objects (node237.html#SECTION00161510000000000000000)\n16 SGI IRIX Specific Services (node238.html#SECTION0017000000000000000000)\n- 16.1 Built-in Module al (node239.html#SECTION0017100000000000000000)\n- Configuration Objects (node240.html#SECTION0017110000000000000000)\nPort Objects (node241.html#SECTION0017120000000000000000)\n16.2 Standard Module AL (node242.html#SECTION0017200000000000000000)\n16.3 Built-in Module cd (node243.html#SECTION0017300000000000000000)\n16.4 Built-in Module fl (node244.html#SECTION0017400000000000000000)\n- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)\nForm Objects (node246.html#SECTION0017420000000000000000)\nFORMS Objects (node247.html#SECTION0017430000000000000000)\n16.5 Standard Module FL (node248.html#SECTION0017500000000000000000)\n16.6 Standard Module flp (node249.html#SECTION0017600000000000000000)\n16.7 Built-in Module fm (node250.html#SECTION0017700000000000000000)\n16.8 Built-in Module gl (node251.html#SECTION0017800000000000000000)\n16.9 Standard Modules GL and DEVICE (node252.html#SECTION0017900000000000000000)\n16.10 Built-in Module imgfile (node253.html#SECTION00171000000000000000000)\n17 SunOS Specific Services (node254.html#SECTION0018000000000000000000)\n- 17.1 Built-in Module sunaudiodev (node255.html#SECTION0018100000000000000000)\n- Audio Device Objects (node256.html#SECTION0018110000000000000000)\n18 Undocumented Modules (node257.html#SECTION0019000000000000000000)\n- 18.1 Fundamental, and pretty straightforward to document (node258.html#SECTION0019100000000000000000)\n18.2 Frameworks; somewhat harder to document, but well worth the effort (node259.html#SECTION0019200000000000000000)\n18.3 Stuff useful to a lot of people, including the CGI crowd (node260.html#SECTION0019300000000000000000)\n18.4 Miscellaneous useful utilities (node261.html#SECTION0019400000000000000000)\n18.5 Parsing Python (node262.html#SECTION0019500000000000000000)\n18.6 Platform specific modules (node263.html#SECTION0019600000000000000000)\n18.7 Code objects and files, debugger etc. (node264.html#SECTION0019700000000000000000)\n18.8 Multimedia (node265.html#SECTION0019800000000000000000)\n18.9 Oddities (node266.html#SECTION0019900000000000000000)\n18.10 Obsolete (node267.html#SECTION00191000000000000000000)\n18.11 Extension modules (node268.html#SECTION00191100000000000000000)\nModule Index (node269.html#SECTION0020000000000000000000)\nIndex (node270.html#SECTION0021000000000000000000)\nAbout this document ... (node271.html#SECTION0022000000000000000000)\n---\nnode1.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 21053, "url": "https://docs.python.org/1.5/lib/index.html"} {"title": "Python Library Reference", "text": "node1.html\nnode1.html\nnode270.html\n---\n# Python Library Reference\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE 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 describes the exact syntax and\nsemantics of the language, it does not describe the standard library\nthat is distributed with the language, and which greatly enhances its\nimmediate usability. This library contains built-in modules (written\nin C) that provide access to system functionality such as file I/O\nthat would otherwise be inaccessible to Python programmers, as well as\nmodules written in Python that provide standardized solutions for many\nproblems that occur in everyday programming. Some of these modules\nare explicitly designed to encourage and enhance the portability of\nPython 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 Python Tutorial; the\nPython Reference Manual remains the highest authority on\nsyntactic and semantic questions. Finally, the manual entitled\nExtending and Embedding the Python Interpreter describes how to\nadd new extensions to Python and how to embed it in other applications.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Introduction (node2.html#SECTION002000000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION003000000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION003100000000000000000)\n- Truth Value Testing (node5.html#SECTION003110000000000000000)\nBoolean Operations (node6.html#SECTION003120000000000000000)\nComparisons (node7.html#SECTION003130000000000000000)\nNumeric Types (node8.html#SECTION003140000000000000000)\nSequence Types (node10.html#SECTION003150000000000000000)\nMapping Types (node13.html#SECTION003160000000000000000)\nOther Built-in Types (node14.html#SECTION003170000000000000000)\nSpecial Attributes (node24.html#SECTION003180000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION003200000000000000000)\n2.3 Built-in Functions (node26.html#SECTION003300000000000000000)\n3 Python Services (node27.html#SECTION004000000000000000000)\n- 3.1 Built-in Module sys (node28.html#SECTION004100000000000000000)\n3.2 Standard Module types (node29.html#SECTION004200000000000000000)\n3.3 Standard Modules UserDict and UserList (node30.html#SECTION004300000000000000000)\n3.4 Built-in Module operator (node31.html#SECTION004400000000000000000)\n3.5 Standard Module traceback (node32.html#SECTION004500000000000000000)\n3.6 Standard Module pickle (node33.html#SECTION004600000000000000000)\nStandard Module copy_reg (node34.html#SECTION004700000000000000000)\n3.8 Standard Module shelve (node35.html#SECTION004800000000000000000)\n3.9 Standard Module copy (node36.html#SECTION004900000000000000000)\n3.10 Built-in Module marshal (node37.html#SECTION0041000000000000000000)\n3.11 Built-in Module imp (node38.html#SECTION0041100000000000000000)\n- Examples (node39.html#SECTION0041110000000000000000)\n3.12 Standard Module ni (node40.html#SECTION0041200000000000000000)\n3.13 Built-in Module parser (node41.html#SECTION0041300000000000000000)\n- Creating AST Objects (node42.html#SECTION0041310000000000000000)\nConverting AST Objects (node43.html#SECTION0041320000000000000000)\nQueries on AST Objects (node44.html#SECTION0041330000000000000000)\nExceptions and Error Handling (node45.html#SECTION0041340000000000000000)\nAST Objects (node46.html#SECTION0041350000000000000000)\nExamples (node47.html#SECTION0041360000000000000000)\n3.14 Standard Module symbol (node50.html#SECTION0041400000000000000000)\n3.15 Standard Module token (node51.html#SECTION0041500000000000000000)\n3.16 Standard Module keyword (node52.html#SECTION0041600000000000000000)\n3.17 Standard Module code (node53.html#SECTION0041700000000000000000)\n3.18 Standard Module pprint (node54.html#SECTION0041800000000000000000)\n- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)\n3.19 Standard Module dis (node56.html#SECTION0041900000000000000000)\n- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)\n3.20 Standard Module site (node58.html#SECTION0042000000000000000000)\n3.21 Standard Module user (node59.html#SECTION0042100000000000000000)\nBuilt-in Module __builtin__ (node60.html#SECTION0042200000000000000000)\nBuilt-in Module __main__ (node61.html#SECTION0042300000000000000000)\n4 String Services (node62.html#SECTION005000000000000000000)\n- 4.1 Standard Module string (node63.html#SECTION005100000000000000000)\n4.2 Built-in Module re (node64.html#SECTION005200000000000000000)\n- Regular Expression Syntax (node65.html#SECTION005210000000000000000)\nModule Contents (node66.html#SECTION005220000000000000000)\nRegular Expression Objects (node67.html#SECTION005230000000000000000)\nMatch Objects (node68.html#SECTION005240000000000000000)\n4.3 Built-in Module regex (node69.html#SECTION005300000000000000000)\n- Regular Expressions (node70.html#SECTION005310000000000000000)\nModule Contents (node71.html#SECTION005320000000000000000)\n4.4 Standard Module regsub (node72.html#SECTION005400000000000000000)\n4.5 Built-in Module struct (node73.html#SECTION005500000000000000000)\n4.6 Standard Module StringIO (node74.html#SECTION005600000000000000000)\n4.7 Built-in Module soundex (node75.html#SECTION005700000000000000000)\n5 Miscellaneous Services (node76.html#SECTION006000000000000000000)\n- 5.1 Built-in Module math (node77.html#SECTION006100000000000000000)\n5.2 Built-in Module cmath (node78.html#SECTION006200000000000000000)\n5.3 Standard Module whrandom (node79.html#SECTION006300000000000000000)\n5.4 Standard Module random (node80.html#SECTION006400000000000000000)\n5.5 Standard Module rand (node81.html#SECTION006500000000000000000)\n5.6 Built-in Module array (node82.html#SECTION006600000000000000000)\n6 Generic Operating System Services (node83.html#SECTION007000000000000000000)\n- 6.1 Standard Module os (node84.html#SECTION007100000000000000000)\n6.2 Built-in Module time (node85.html#SECTION007200000000000000000)\n6.3 Standard Module getopt (node86.html#SECTION007300000000000000000)\n6.4 Standard Module tempfile (node87.html#SECTION007400000000000000000)\n6.5 Standard Module errno (node88.html#SECTION007500000000000000000)\n6.6 Standard Module glob (node89.html#SECTION007600000000000000000)\n6.7 Standard Module fnmatch (node90.html#SECTION007700000000000000000)\n6.8 Standard Module locale (node91.html#SECTION007800000000000000000)\n7 Optional Operating System Services (node92.html#SECTION008000000000000000000)\n- 7.1 Built-in Module signal (node93.html#SECTION008100000000000000000)\n7.2 Built-in Module socket (node94.html#SECTION008200000000000000000)\n- Socket Objects (node95.html#SECTION008210000000000000000)\nExample (node96.html#SECTION008220000000000000000)\n7.3 Built-in Module select (node97.html#SECTION008300000000000000000)\n7.4 Built-in Module thread (node98.html#SECTION008400000000000000000)\n7.5 Standard Module Queue (node99.html#SECTION008500000000000000000)\n- Queue Objects (node100.html#SECTION008510000000000000000)\n7.6 Standard Modules anydbm and dumbdbm (node101.html#SECTION008600000000000000000)\n7.7 Standard Module whichdb (node102.html#SECTION008700000000000000000)\n7.8 Built-in Module zlib (node103.html#SECTION008800000000000000000)\n7.9 Built-in Module gzip (node104.html#SECTION008900000000000000000)\n8 Unix Specific Services (node105.html#SECTION009000000000000000000)\n- 8.1 Built-in Module posix (node106.html#SECTION009100000000000000000)\n8.2 Standard Module posixpath (node107.html#SECTION009200000000000000000)\n8.3 Built-in Module pwd (node108.html#SECTION009300000000000000000)\n8.4 Built-in Module grp (node109.html#SECTION009400000000000000000)\n8.5 Built-in Module crypt (node110.html#SECTION009500000000000000000)\n8.6 Built-in Module dbm (node111.html#SECTION009600000000000000000)\n8.7 Built-in Module gdbm (node112.html#SECTION009700000000000000000)\n8.8 Built-in Module termios (node113.html#SECTION009800000000000000000)\n- Example (node114.html#SECTION009810000000000000000)\n8.9 Standard Module TERMIOS (node115.html#SECTION009900000000000000000)\n8.10 Built-in Module fcntl (node116.html#SECTION0091000000000000000000)\n8.11 Standard Module posixfile (node117.html#SECTION0091100000000000000000)\n8.12 Built-in Module resource (node118.html#SECTION0091200000000000000000)\n- Resource Limits (node119.html#SECTION0091210000000000000000)\nResource Usage (node120.html#SECTION0091220000000000000000)\n8.13 Built-in Module syslog (node121.html#SECTION0091300000000000000000)\n8.14 Standard Module stat (node122.html#SECTION0091400000000000000000)\n8.15 Standard Module commands (node123.html#SECTION0091500000000000000000)\n9 The Python Debugger (node124.html#SECTION0010000000000000000000)\n- 9.1 Debugger Commands (node125.html#SECTION0010100000000000000000)\n9.2 How It Works (node126.html#SECTION0010200000000000000000)\n10 The Python Profiler (node127.html#SECTION0011000000000000000000)\n- 10.1 Introduction to the profiler (node128.html#SECTION0011100000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node129.html#SECTION0011200000000000000000)\n10.3 Instant Users Manual (node130.html#SECTION0011300000000000000000)\n10.4 What Is Deterministic Profiling? (node131.html#SECTION0011400000000000000000)\n10.5 Reference Manual (node132.html#SECTION0011500000000000000000)\n- The Stats Class (node133.html#SECTION0011510000000000000000)\n10.6 Limitations (node134.html#SECTION0011600000000000000000)\n10.7 Calibration (node135.html#SECTION0011700000000000000000)\n10.8 Extensions - Deriving Better Profilers (node136.html#SECTION0011800000000000000000)\n- OldProfile Class (node137.html#SECTION0011810000000000000000)\nHotProfile Class (node138.html#SECTION0011820000000000000000)\n11 Internet and WWW Services (node139.html#SECTION0012000000000000000000)\n- 11.1 Standard Module cgi (node140.html#SECTION0012100000000000000000)\n- Introduction (node141.html#SECTION0012110000000000000000)\nUsing the cgi module (node142.html#SECTION0012120000000000000000)\nOld classes (node143.html#SECTION0012130000000000000000)\nFunctions (node144.html#SECTION0012140000000000000000)\nCaring about security (node145.html#SECTION0012150000000000000000)\nInstalling your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)\nTesting your CGI script (node147.html#SECTION0012170000000000000000)\nDebugging CGI scripts (node148.html#SECTION0012180000000000000000)\nCommon problems and solutions (node149.html#SECTION0012190000000000000000)\n11.2 Standard Module urllib (node150.html#SECTION0012200000000000000000)\n11.3 Standard Module httplib (node151.html#SECTION0012300000000000000000)\n- HTTP Objects (node152.html#SECTION0012310000000000000000)\nExample (node153.html#SECTION0012320000000000000000)\n11.4 Standard Module ftplib (node154.html#SECTION0012400000000000000000)\n- FTP Objects (node155.html#SECTION0012410000000000000000)\n11.5 Standard Module gopherlib (node156.html#SECTION0012500000000000000000)\n11.6 Standard Module nntplib (node157.html#SECTION0012600000000000000000)\n- NNTP Objects (node158.html#SECTION0012610000000000000000)\n11.7 Standard Module urlparse (node159.html#SECTION0012700000000000000000)\n11.8 Standard Module sgmllib (node160.html#SECTION0012800000000000000000)\n11.9 Standard Module htmllib (node161.html#SECTION0012900000000000000000)\n11.10 Standard Module xmllib (node162.html#SECTION00121000000000000000000)\n11.11 Standard Module formatter (node163.html#SECTION00121100000000000000000)\n- The Formatter Interface (node164.html#SECTION00121110000000000000000)\nFormatter Implementations (node165.html#SECTION00121120000000000000000)\nThe Writer Interface (node166.html#SECTION00121130000000000000000)\nWriter Implementations (node167.html#SECTION00121140000000000000000)\n11.12 Standard Module rfc822 (node168.html#SECTION00121200000000000000000)\n- Message Objects (node169.html#SECTION00121210000000000000000)\n11.13 Standard Module mimetools (node170.html#SECTION00121300000000000000000)\n- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)\n11.14 Standard Module binhex (node172.html#SECTION00121400000000000000000)\n- Notes (node173.html#SECTION00121410000000000000000)\n11.15 Standard Module uu (node174.html#SECTION00121500000000000000000)\n11.16 Built-in Module binascii (node175.html#SECTION00121600000000000000000)\n11.17 Standard Module xdrlib (node176.html#SECTION00121700000000000000000)\n- Packer Objects (node177.html#SECTION00121710000000000000000)\nUnpacker Objects (node178.html#SECTION00121720000000000000000)\nExceptions (node179.html#SECTION00121730000000000000000)\n11.18 Standard Module mailcap (node180.html#SECTION00121800000000000000000)\n11.19 Standard Module base64 (node181.html#SECTION00121900000000000000000)\n11.20 Standard Module quopri (node182.html#SECTION00122000000000000000000)\n11.21 Standard Module SocketServer (node183.html#SECTION00122100000000000000000)\n11.22 Standard Module mailbox (node184.html#SECTION00122200000000000000000)\n- Mailbox Objects (node185.html#SECTION00122210000000000000000)\n11.23 Standard Module mimify (node186.html#SECTION00122300000000000000000)\n11.24 Standard Module BaseHTTPServer (node187.html#SECTION00122400000000000000000)\n12 Restricted Execution (node188.html#SECTION0013000000000000000000)\n- 12.1 Standard Module rexec (node189.html#SECTION0013100000000000000000)\n- An example (node190.html#SECTION0013110000000000000000)\n12.2 Standard Module Bastion (node191.html#SECTION0013200000000000000000)\n13 Multimedia Services (node192.html#SECTION0014000000000000000000)\n- 13.1 Built-in Module audioop (node193.html#SECTION0014100000000000000000)\n13.2 Built-in Module imageop (node194.html#SECTION0014200000000000000000)\n13.3 Standard Module aifc (node195.html#SECTION0014300000000000000000)\n13.4 Built-in Module jpeg (node196.html#SECTION0014400000000000000000)\n13.5 Built-in Module rgbimg (node197.html#SECTION0014500000000000000000)\n13.6 Standard Module imghdr (node198.html#SECTION0014600000000000000000)\n14 Cryptographic Services (node199.html#SECTION0015000000000000000000)\n- 14.1 Built-in Module md5 (node200.html#SECTION0015100000000000000000)\n14.2 Built-in Module mpz (node201.html#SECTION0015200000000000000000)\n14.3 Built-in Module rotor (node202.html#SECTION0015300000000000000000)\n15 Macintosh Specific Services (node203.html#SECTION0016000000000000000000)\n- 15.1 Built-in Module mac (node204.html#SECTION0016100000000000000000)\n15.2 Standard Module macpath (node205.html#SECTION0016200000000000000000)\n15.3 Built-in Module ctb (node206.html#SECTION0016300000000000000000)\n- connection object (node207.html#SECTION0016310000000000000000)\n15.4 Built-in Module macconsole (node208.html#SECTION0016400000000000000000)\n- macconsole options object (node209.html#SECTION0016410000000000000000)\nconsole window object (node210.html#SECTION0016420000000000000000)\n15.5 Built-in Module macdnr (node211.html#SECTION0016500000000000000000)\n- dnr result object (node212.html#SECTION0016510000000000000000)\n15.6 Built-in Module macfs (node213.html#SECTION0016600000000000000000)\n- FSSpec objects (node214.html#SECTION0016610000000000000000)\nalias objects (node215.html#SECTION0016620000000000000000)\nFInfo objects (node216.html#SECTION0016630000000000000000)\n15.7 Standard Module ic (node217.html#SECTION0016700000000000000000)\n- IC objects (node218.html#SECTION0016710000000000000000)\n15.8 Built-in Module MacOS (node219.html#SECTION0016800000000000000000)\n15.9 Standard Module macostools (node220.html#SECTION0016900000000000000000)\n15.10 Standard Module findertools (node221.html#SECTION00161000000000000000000)\n15.11 Built-in Module mactcp (node222.html#SECTION00161100000000000000000)\n- TCP Stream Objects (node223.html#SECTION00161110000000000000000)\nTCP Status Objects (node224.html#SECTION00161120000000000000000)\nUDP Stream Objects (node225.html#SECTION00161130000000000000000)\n15.12 Built-in Module macspeech (node226.html#SECTION00161200000000000000000)\n- voice objects (node227.html#SECTION00161210000000000000000)\nspeech channel objects (node228.html#SECTION00161220000000000000000)\n15.13 Standard Module EasyDialogs (node229.html#SECTION00161300000000000000000)\n15.14 Standard Module FrameWork (node230.html#SECTION00161400000000000000000)\n- Application objects (node231.html#SECTION00161410000000000000000)\nWindow Objects (node232.html#SECTION00161420000000000000000)\nControlsWindow Object (node233.html#SECTION00161430000000000000000)\nScrolledWindow Object (node234.html#SECTION00161440000000000000000)\nDialogWindow Objects (node235.html#SECTION00161450000000000000000)\n15.15 Standard Module MiniAEFrame (node236.html#SECTION00161500000000000000000)\n- AEServer Objects (node237.html#SECTION00161510000000000000000)\n16 SGI IRIX Specific Services (node238.html#SECTION0017000000000000000000)\n- 16.1 Built-in Module al (node239.html#SECTION0017100000000000000000)\n- Configuration Objects (node240.html#SECTION0017110000000000000000)\nPort Objects (node241.html#SECTION0017120000000000000000)\n16.2 Standard Module AL (node242.html#SECTION0017200000000000000000)\n16.3 Built-in Module cd (node243.html#SECTION0017300000000000000000)\n16.4 Built-in Module fl (node244.html#SECTION0017400000000000000000)\n- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)\nForm Objects (node246.html#SECTION0017420000000000000000)\nFORMS Objects (node247.html#SECTION0017430000000000000000)\n16.5 Standard Module FL (node248.html#SECTION0017500000000000000000)\n16.6 Standard Module flp (node249.html#SECTION0017600000000000000000)\n16.7 Built-in Module fm (node250.html#SECTION0017700000000000000000)\n16.8 Built-in Module gl (node251.html#SECTION0017800000000000000000)\n16.9 Standard Modules GL and DEVICE (node252.html#SECTION0017900000000000000000)\n16.10 Built-in Module imgfile (node253.html#SECTION00171000000000000000000)\n17 SunOS Specific Services (node254.html#SECTION0018000000000000000000)\n- 17.1 Built-in Module sunaudiodev (node255.html#SECTION0018100000000000000000)\n- Audio Device Objects (node256.html#SECTION0018110000000000000000)\n18 Undocumented Modules (node257.html#SECTION0019000000000000000000)\n- 18.1 Fundamental, and pretty straightforward to document (node258.html#SECTION0019100000000000000000)\n18.2 Frameworks; somewhat harder to document, but well worth the effort (node259.html#SECTION0019200000000000000000)\n18.3 Stuff useful to a lot of people, including the CGI crowd (node260.html#SECTION0019300000000000000000)\n18.4 Miscellaneous useful utilities (node261.html#SECTION0019400000000000000000)\n18.5 Parsing Python (node262.html#SECTION0019500000000000000000)\n18.6 Platform specific modules (node263.html#SECTION0019600000000000000000)\n18.7 Code objects and files, debugger etc. (node264.html#SECTION0019700000000000000000)\n18.8 Multimedia (node265.html#SECTION0019800000000000000000)\n18.9 Oddities (node266.html#SECTION0019900000000000000000)\n18.10 Obsolete (node267.html#SECTION00191000000000000000000)\n18.11 Extension modules (node268.html#SECTION00191100000000000000000)\nModule Index (node269.html#SECTION0020000000000000000000)\nIndex (node270.html#SECTION0021000000000000000000)\nAbout this document ... (node271.html#SECTION0022000000000000000000)\n---\nnode1.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 21053, "url": "https://docs.python.org/1.5/lib/lib.html"} {"title": "Contents", "text": "node2.html\nlib.html\nlib.html\nnode270.html\n---\n## Contents\n- 1 Introduction (node2.html#SECTION002000000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION003000000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION003100000000000000000)\n- Truth Value Testing (node5.html#SECTION003110000000000000000)\nBoolean Operations (node6.html#SECTION003120000000000000000)\nComparisons (node7.html#SECTION003130000000000000000)\nNumeric Types (node8.html#SECTION003140000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)\nSequence Types (node10.html#SECTION003150000000000000000)\n- More String Operations (node11.html#SECTION003151000000000000000)\nMutable Sequence Types (node12.html#SECTION003152000000000000000)\nMapping Types (node13.html#SECTION003160000000000000000)\nOther Built-in Types (node14.html#SECTION003170000000000000000)\n- Modules (node15.html#SECTION003171000000000000000)\nClasses and Class Instances (node16.html#SECTION003172000000000000000)\nFunctions (node17.html#SECTION003173000000000000000)\nMethods (node18.html#SECTION003174000000000000000)\nCode Objects (node19.html#SECTION003175000000000000000)\nType Objects (node20.html#SECTION003176000000000000000)\nThe Null Object (node21.html#SECTION003177000000000000000)\nFile Objects (node22.html#SECTION003178000000000000000)\nInternal Objects (node23.html#SECTION003179000000000000000)\nSpecial Attributes (node24.html#SECTION003180000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION003200000000000000000)\n2.3 Built-in Functions (node26.html#SECTION003300000000000000000)\n3 Python Services (node27.html#SECTION004000000000000000000)\n- 3.1 Built-in Module sys (node28.html#SECTION004100000000000000000)\n3.2 Standard Module types (node29.html#SECTION004200000000000000000)\n3.3 Standard Modules UserDict and UserList (node30.html#SECTION004300000000000000000)\n3.4 Built-in Module operator (node31.html#SECTION004400000000000000000)\n3.5 Standard Module traceback (node32.html#SECTION004500000000000000000)\n3.6 Standard Module pickle (node33.html#SECTION004600000000000000000)\nStandard Module copy_reg (node34.html#SECTION004700000000000000000)\n3.8 Standard Module shelve (node35.html#SECTION004800000000000000000)\n3.9 Standard Module copy (node36.html#SECTION004900000000000000000)\n3.10 Built-in Module marshal (node37.html#SECTION0041000000000000000000)\n3.11 Built-in Module imp (node38.html#SECTION0041100000000000000000)\n- Examples (node39.html#SECTION0041110000000000000000)\n3.12 Standard Module ni (node40.html#SECTION0041200000000000000000)\n3.13 Built-in Module parser (node41.html#SECTION0041300000000000000000)\n- Creating AST Objects (node42.html#SECTION0041310000000000000000)\nConverting AST Objects (node43.html#SECTION0041320000000000000000)\nQueries on AST Objects (node44.html#SECTION0041330000000000000000)\nExceptions and Error Handling (node45.html#SECTION0041340000000000000000)\nAST Objects (node46.html#SECTION0041350000000000000000)\nExamples (node47.html#SECTION0041360000000000000000)\n- Emulation of compile() (node48.html#SECTION0041361000000000000000)\nInformation Discovery (node49.html#SECTION0041362000000000000000)\n3.14 Standard Module symbol (node50.html#SECTION0041400000000000000000)\n3.15 Standard Module token (node51.html#SECTION0041500000000000000000)\n3.16 Standard Module keyword (node52.html#SECTION0041600000000000000000)\n3.17 Standard Module code (node53.html#SECTION0041700000000000000000)\n3.18 Standard Module pprint (node54.html#SECTION0041800000000000000000)\n- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)\n3.19 Standard Module dis (node56.html#SECTION0041900000000000000000)\n- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)\n3.20 Standard Module site (node58.html#SECTION0042000000000000000000)\n3.21 Standard Module user (node59.html#SECTION0042100000000000000000)\nBuilt-in Module __builtin__ (node60.html#SECTION0042200000000000000000)\nBuilt-in Module __main__ (node61.html#SECTION0042300000000000000000)\n4 String Services (node62.html#SECTION005000000000000000000)\n- 4.1 Standard Module string (node63.html#SECTION005100000000000000000)\n4.2 Built-in Module re (node64.html#SECTION005200000000000000000)\n- Regular Expression Syntax (node65.html#SECTION005210000000000000000)\nModule Contents (node66.html#SECTION005220000000000000000)\nRegular Expression Objects (node67.html#SECTION005230000000000000000)\nMatch Objects (node68.html#SECTION005240000000000000000)\n4.3 Built-in Module regex (node69.html#SECTION005300000000000000000)\n- Regular Expressions (node70.html#SECTION005310000000000000000)\nModule Contents (node71.html#SECTION005320000000000000000)\n4.4 Standard Module regsub (node72.html#SECTION005400000000000000000)\n4.5 Built-in Module struct (node73.html#SECTION005500000000000000000)\n4.6 Standard Module StringIO (node74.html#SECTION005600000000000000000)\n4.7 Built-in Module soundex (node75.html#SECTION005700000000000000000)\n5 Miscellaneous Services (node76.html#SECTION006000000000000000000)\n- 5.1 Built-in Module math (node77.html#SECTION006100000000000000000)\n5.2 Built-in Module cmath (node78.html#SECTION006200000000000000000)\n5.3 Standard Module whrandom (node79.html#SECTION006300000000000000000)\n5.4 Standard Module random (node80.html#SECTION006400000000000000000)\n5.5 Standard Module rand (node81.html#SECTION006500000000000000000)\n5.6 Built-in Module array (node82.html#SECTION006600000000000000000)\n6 Generic Operating System Services (node83.html#SECTION007000000000000000000)\n- 6.1 Standard Module os (node84.html#SECTION007100000000000000000)\n6.2 Built-in Module time (node85.html#SECTION007200000000000000000)\n6.3 Standard Module getopt (node86.html#SECTION007300000000000000000)\n6.4 Standard Module tempfile (node87.html#SECTION007400000000000000000)\n6.5 Standard Module errno (node88.html#SECTION007500000000000000000)\n6.6 Standard Module glob (node89.html#SECTION007600000000000000000)\n6.7 Standard Module fnmatch (node90.html#SECTION007700000000000000000)\n6.8 Standard Module locale (node91.html#SECTION007800000000000000000)\n7 Optional Operating System Services (node92.html#SECTION008000000000000000000)\n- 7.1 Built-in Module signal (node93.html#SECTION008100000000000000000)\n7.2 Built-in Module socket (node94.html#SECTION008200000000000000000)\n- Socket Objects (node95.html#SECTION008210000000000000000)\nExample (node96.html#SECTION008220000000000000000)\n7.3 Built-in Module select (node97.html#SECTION008300000000000000000)\n7.4 Built-in Module thread (node98.html#SECTION008400000000000000000)\n7.5 Standard Module Queue (node99.html#SECTION008500000000000000000)\n- Queue Objects (node100.html#SECTION008510000000000000000)\n7.6 Standard Modules anydbm and dumbdbm (node101.html#SECTION008600000000000000000)\n7.7 Standard Module whichdb (node102.html#SECTION008700000000000000000)\n7.8 Built-in Module zlib (node103.html#SECTION008800000000000000000)\n7.9 Built-in Module gzip (node104.html#SECTION008900000000000000000)\n8 Unix Specific Services (node105.html#SECTION009000000000000000000)\n- 8.1 Built-in Module posix (node106.html#SECTION009100000000000000000)\n8.2 Standard Module posixpath (node107.html#SECTION009200000000000000000)\n8.3 Built-in Module pwd (node108.html#SECTION009300000000000000000)\n8.4 Built-in Module grp (node109.html#SECTION009400000000000000000)\n8.5 Built-in Module crypt (node110.html#SECTION009500000000000000000)\n8.6 Built-in Module dbm (node111.html#SECTION009600000000000000000)\n8.7 Built-in Module gdbm (node112.html#SECTION009700000000000000000)\n8.8 Built-in Module termios (node113.html#SECTION009800000000000000000)\n- Example (node114.html#SECTION009810000000000000000)\n8.9 Standard Module TERMIOS (node115.html#SECTION009900000000000000000)\n8.10 Built-in Module fcntl (node116.html#SECTION0091000000000000000000)\n8.11 Standard Module posixfile (node117.html#SECTION0091100000000000000000)\n8.12 Built-in Module resource (node118.html#SECTION0091200000000000000000)\n- Resource Limits (node119.html#SECTION0091210000000000000000)\nResource Usage (node120.html#SECTION0091220000000000000000)\n8.13 Built-in Module syslog (node121.html#SECTION0091300000000000000000)\n8.14 Standard Module stat (node122.html#SECTION0091400000000000000000)\n8.15 Standard Module commands (node123.html#SECTION0091500000000000000000)\n9 The Python Debugger (node124.html#SECTION0010000000000000000000)\n- 9.1 Debugger Commands (node125.html#SECTION0010100000000000000000)\n9.2 How It Works (node126.html#SECTION0010200000000000000000)\n10 The Python Profiler (node127.html#SECTION0011000000000000000000)\n- 10.1 Introduction to the profiler (node128.html#SECTION0011100000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node129.html#SECTION0011200000000000000000)\n10.3 Instant Users Manual (node130.html#SECTION0011300000000000000000)\n10.4 What Is Deterministic Profiling? (node131.html#SECTION0011400000000000000000)\n10.5 Reference Manual (node132.html#SECTION0011500000000000000000)\n- The Stats Class (node133.html#SECTION0011510000000000000000)\n10.6 Limitations (node134.html#SECTION0011600000000000000000)\n10.7 Calibration (node135.html#SECTION0011700000000000000000)\n10.8 Extensions - Deriving Better Profilers (node136.html#SECTION0011800000000000000000)\n- OldProfile Class (node137.html#SECTION0011810000000000000000)\nHotProfile Class (node138.html#SECTION0011820000000000000000)\n11 Internet and WWW Services (node139.html#SECTION0012000000000000000000)\n- 11.1 Standard Module cgi (node140.html#SECTION0012100000000000000000)\n- Introduction (node141.html#SECTION0012110000000000000000)\nUsing the cgi module (node142.html#SECTION0012120000000000000000)\nOld classes (node143.html#SECTION0012130000000000000000)\nFunctions (node144.html#SECTION0012140000000000000000)\nCaring about security (node145.html#SECTION0012150000000000000000)\nInstalling your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)\nTesting your CGI script (node147.html#SECTION0012170000000000000000)\nDebugging CGI scripts (node148.html#SECTION0012180000000000000000)\nCommon problems and solutions (node149.html#SECTION0012190000000000000000)\n11.2 Standard Module urllib (node150.html#SECTION0012200000000000000000)\n11.3 Standard Module httplib (node151.html#SECTION0012300000000000000000)\n- HTTP Objects (node152.html#SECTION0012310000000000000000)\nExample (node153.html#SECTION0012320000000000000000)\n11.4 Standard Module ftplib (node154.html#SECTION0012400000000000000000)\n- FTP Objects (node155.html#SECTION0012410000000000000000)\n11.5 Standard Module gopherlib (node156.html#SECTION0012500000000000000000)\n11.6 Standard Module nntplib (node157.html#SECTION0012600000000000000000)\n- NNTP Objects (node158.html#SECTION0012610000000000000000)\n11.7 Standard Module urlparse (node159.html#SECTION0012700000000000000000)\n11.8 Standard Module sgmllib (node160.html#SECTION0012800000000000000000)\n11.9 Standard Module htmllib (node161.html#SECTION0012900000000000000000)\n11.10 Standard Module xmllib (node162.html#SECTION00121000000000000000000)\n11.11 Standard Module formatter (node163.html#SECTION00121100000000000000000)\n- The Formatter Interface (node164.html#SECTION00121110000000000000000)\nFormatter Implementations (node165.html#SECTION00121120000000000000000)\nThe Writer Interface (node166.html#SECTION00121130000000000000000)\nWriter Implementations (node167.html#SECTION00121140000000000000000)\n11.12 Standard Module rfc822 (node168.html#SECTION00121200000000000000000)\n- Message Objects (node169.html#SECTION00121210000000000000000)\n11.13 Standard Module mimetools (node170.html#SECTION00121300000000000000000)\n- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)\n11.14 Standard Module binhex (node172.html#SECTION00121400000000000000000)\n- Notes (node173.html#SECTION00121410000000000000000)\n11.15 Standard Module uu (node174.html#SECTION00121500000000000000000)\n11.16 Built-in Module binascii (node175.html#SECTION00121600000000000000000)\n11.17 Standard Module xdrlib (node176.html#SECTION00121700000000000000000)\n- Packer Objects (node177.html#SECTION00121710000000000000000)\nUnpacker Objects (node178.html#SECTION00121720000000000000000)\nExceptions (node179.html#SECTION00121730000000000000000)\n11.18 Standard Module mailcap (node180.html#SECTION00121800000000000000000)\n11.19 Standard Module base64 (node181.html#SECTION00121900000000000000000)\n11.20 Standard Module quopri (node182.html#SECTION00122000000000000000000)\n11.21 Standard Module SocketServer (node183.html#SECTION00122100000000000000000)\n11.22 Standard Module mailbox (node184.html#SECTION00122200000000000000000)\n- Mailbox Objects (node185.html#SECTION00122210000000000000000)\n11.23 Standard Module mimify (node186.html#SECTION00122300000000000000000)\n11.24 Standard Module BaseHTTPServer (node187.html#SECTION00122400000000000000000)\n12 Restricted Execution (node188.html#SECTION0013000000000000000000)\n- 12.1 Standard Module rexec (node189.html#SECTION0013100000000000000000)\n- An example (node190.html#SECTION0013110000000000000000)\n12.2 Standard Module Bastion (node191.html#SECTION0013200000000000000000)\n13 Multimedia Services (node192.html#SECTION0014000000000000000000)\n- 13.1 Built-in Module audioop (node193.html#SECTION0014100000000000000000)\n13.2 Built-in Module imageop (node194.html#SECTION0014200000000000000000)\n13.3 Standard Module aifc (node195.html#SECTION0014300000000000000000)\n13.4 Built-in Module jpeg (node196.html#SECTION0014400000000000000000)\n13.5 Built-in Module rgbimg (node197.html#SECTION0014500000000000000000)\n13.6 Standard Module imghdr (node198.html#SECTION0014600000000000000000)\n14 Cryptographic Services (node199.html#SECTION0015000000000000000000)\n- 14.1 Built-in Module md5 (node200.html#SECTION0015100000000000000000)\n14.2 Built-in Module mpz (node201.html#SECTION0015200000000000000000)\n14.3 Built-in Module rotor (node202.html#SECTION0015300000000000000000)\n15 Macintosh Specific Services (node203.html#SECTION0016000000000000000000)\n- 15.1 Built-in Module mac (node204.html#SECTION0016100000000000000000)\n15.2 Standard Module macpath (node205.html#SECTION0016200000000000000000)\n15.3 Built-in Module ctb (node206.html#SECTION0016300000000000000000)\n- connection object (node207.html#SECTION0016310000000000000000)\n15.4 Built-in Module macconsole (node208.html#SECTION0016400000000000000000)\n- macconsole options object (node209.html#SECTION0016410000000000000000)\nconsole window object (node210.html#SECTION0016420000000000000000)\n15.5 Built-in Module macdnr (node211.html#SECTION0016500000000000000000)\n- dnr result object (node212.html#SECTION0016510000000000000000)\n15.6 Built-in Module macfs (node213.html#SECTION0016600000000000000000)\n- FSSpec objects (node214.html#SECTION0016610000000000000000)\nalias objects (node215.html#SECTION0016620000000000000000)\nFInfo objects (node216.html#SECTION0016630000000000000000)\n15.7 Standard Module ic (node217.html#SECTION0016700000000000000000)\n- IC objects (node218.html#SECTION0016710000000000000000)\n15.8 Built-in Module MacOS (node219.html#SECTION0016800000000000000000)\n15.9 Standard Module macostools (node220.html#SECTION0016900000000000000000)\n15.10 Standard Module findertools (node221.html#SECTION00161000000000000000000)\n15.11 Built-in Module mactcp (node222.html#SECTION00161100000000000000000)\n- TCP Stream Objects (node223.html#SECTION00161110000000000000000)\nTCP Status Objects (node224.html#SECTION00161120000000000000000)\nUDP Stream Objects (node225.html#SECTION00161130000000000000000)\n15.12 Built-in Module macspeech (node226.html#SECTION00161200000000000000000)\n- voice objects (node227.html#SECTION00161210000000000000000)\nspeech channel objects (node228.html#SECTION00161220000000000000000)\n15.13 Standard Module EasyDialogs (node229.html#SECTION00161300000000000000000)\n15.14 Standard Module FrameWork (node230.html#SECTION00161400000000000000000)\n- Application objects (node231.html#SECTION00161410000000000000000)\nWindow Objects (node232.html#SECTION00161420000000000000000)\nControlsWindow Object (node233.html#SECTION00161430000000000000000)\nScrolledWindow Object (node234.html#SECTION00161440000000000000000)\nDialogWindow Objects (node235.html#SECTION00161450000000000000000)\n15.15 Standard Module MiniAEFrame (node236.html#SECTION00161500000000000000000)\n- AEServer Objects (node237.html#SECTION00161510000000000000000)\n16 SGI IRIX Specific Services (node238.html#SECTION0017000000000000000000)\n- 16.1 Built-in Module al (node239.html#SECTION0017100000000000000000)\n- Configuration Objects (node240.html#SECTION0017110000000000000000)\nPort Objects (node241.html#SECTION0017120000000000000000)\n16.2 Standard Module AL (node242.html#SECTION0017200000000000000000)\n16.3 Built-in Module cd (node243.html#SECTION0017300000000000000000)\n16.4 Built-in Module fl (node244.html#SECTION0017400000000000000000)\n- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)\nForm Objects (node246.html#SECTION0017420000000000000000)\nFORMS Objects (node247.html#SECTION0017430000000000000000)\n16.5 Standard Module FL (node248.html#SECTION0017500000000000000000)\n16.6 Standard Module flp (node249.html#SECTION0017600000000000000000)\n16.7 Built-in Module fm (node250.html#SECTION0017700000000000000000)\n16.8 Built-in Module gl (node251.html#SECTION0017800000000000000000)\n16.9 Standard Modules GL and DEVICE (node252.html#SECTION0017900000000000000000)\n16.10 Built-in Module imgfile (node253.html#SECTION00171000000000000000000)\n17 SunOS Specific Services (node254.html#SECTION0018000000000000000000)\n- 17.1 Built-in Module sunaudiodev (node255.html#SECTION0018100000000000000000)\n- Audio Device Objects (node256.html#SECTION0018110000000000000000)\n18 Undocumented Modules (node257.html#SECTION0019000000000000000000)\n- 18.1 Fundamental, and pretty straightforward to document (node258.html#SECTION0019100000000000000000)\n18.2 Frameworks; somewhat harder to document, but well worth the effort (node259.html#SECTION0019200000000000000000)\n18.3 Stuff useful to a lot of people, including the CGI crowd (node260.html#SECTION0019300000000000000000)\n18.4 Miscellaneous useful utilities (node261.html#SECTION0019400000000000000000)\n18.5 Parsing Python (node262.html#SECTION0019500000000000000000)\n18.6 Platform specific modules (node263.html#SECTION0019600000000000000000)\n18.7 Code objects and files, debugger etc. (node264.html#SECTION0019700000000000000000)\n18.8 Multimedia (node265.html#SECTION0019800000000000000000)\n18.9 Oddities (node266.html#SECTION0019900000000000000000)\n18.10 Obsolete (node267.html#SECTION00191000000000000000000)\n18.11 Extension modules (node268.html#SECTION00191100000000000000000)\nModule Index (node269.html#SECTION0020000000000000000000)\nIndex (node270.html#SECTION0021000000000000000000)\nAbout this document ... (node271.html#SECTION0022000000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 18803, "url": "https://docs.python.org/1.5/lib/node1.html"} {"title": "Sequence Types", "text": "node11.html\nnode4.html\nnode9.html\nnode1.html\nnode270.html\n---\n## 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 Python\nReference Manual for more about string literals. Lists are\nconstructed with square brackets, separating items with commas:\n[a, b, c]. Tuples are constructed by the comma operator (not\nwithin square brackets), with or without enclosing parentheses, but an\nempty tuple must have the enclosing parentheses, e.g.,\na, b, c or (). A single item tuple must have a trailing\ncomma, 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.footnode.html#415\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:\nOperation | Result | Notes\n,\nNotes:\n---\n- More String Operations (node11.html#SECTION003151000000000000000)\nMutable Sequence Types (node12.html#SECTION003152000000000000000)\n---\nnode11.html\nnode4.html\nnode9.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1328, "url": "https://docs.python.org/1.5/lib/node10.html"} {"title": "Queue Objects", "text": "node101.html\nnode99.html\nnode99.html\nnode1.html\nnode270.html\n---\n## 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\ninterface methods are:\n---\nguido@python.org", "python_version": "1.5", "length": 388, "url": "https://docs.python.org/1.5/lib/node100.html"} {"title": "7.6 Standard Modules anydbm and dumbdbm", "text": "node102.html\nnode92.html\nnode100.html\nnode1.html\nnode270.html\n---\n# 7.6 Standard Modules anydbm and dumbdbm\nanydbm is a generic interface to variants of the DBM\ndatabase-DBM, GDBM, or dbhash. If none of these modules is\ninstalled, the slow-but-simple implementation in module dumbdbm\nwill be used. Both modules provide the same interface:\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.\nBoth modules also export the exception error, which is raised\nfor various problems. The anydbm.error exception is simply a\ndifferent name for the error exception of the underlying\nimplementation module used.\n---\nguido@python.org", "python_version": "1.5", "length": 821, "url": "https://docs.python.org/1.5/lib/node101.html"} {"title": "7.7 Standard Module whichdb", "text": "node103.html\nnode92.html\nnode101.html\nnode1.html\nnode270.html\n---\n# 7.7 Standard Module whichdb\nThe single function in this module attempts to guess which of the\nseveral simple database modules available-dbm, gdbm, or\ndbhash-should be used to open a given file.\n---\nguido@python.org", "python_version": "1.5", "length": 282, "url": "https://docs.python.org/1.5/lib/node102.html"} {"title": "7.8 Built-in Module zlib", "text": "node104.html\nnode92.html\nnode102.html\nnode1.html\nnode270.html\n---\n# 7.8 Built-in Module zlib\nFor applications that require data compression, the functions in this\nmodule allow compression and decompression, using the zlib library,\nwhich is based on GNU zip. The zlib library has its own home page at\nhttp://www.cdrom.com/pub/infozip/zlib/.\nVersion 1.0.4 is the most recent version as of December, 1997; use a\nlater version if one is available.\nThe available functions in this module are:\nCompression objects support the following methods:\nDecompression objects support the following methods:\nSee Also:\ngzip (reading and writing `gzip'-format files)\n---\nnode104.html\nnode92.html\nnode102.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 731, "url": "https://docs.python.org/1.5/lib/node103.html"} {"title": "7.9 Built-in Module gzip", "text": "node105.html\nnode92.html\nnode103.html\nnode1.html\nnode270.html\n---\n# 7.9 Built-in Module gzip\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 class\nto read and write `gzip'-format files, automatically compressing\nor decompressing the data so it looks like an ordinary file object.\nGzipFile objects simulate most of the methods of a file\nobject, though it's not possible to use the seek() and\ntell() methods to access the file randomly.\nSee Also:\nzlib (the basic data compression module)\n---\nguido@python.org", "python_version": "1.5", "length": 626, "url": "https://docs.python.org/1.5/lib/node104.html"} {"title": "8 Unix Specific Services", "text": "node106.html\nlib.html\nnode104.html\nnode1.html\nnode270.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:\n---\n- 8.1 Built-in Module posix (node106.html#SECTION009100000000000000000)\n8.2 Standard Module posixpath (node107.html#SECTION009200000000000000000)\n8.3 Built-in Module pwd (node108.html#SECTION009300000000000000000)\n8.4 Built-in Module grp (node109.html#SECTION009400000000000000000)\n8.5 Built-in Module crypt (node110.html#SECTION009500000000000000000)\n8.6 Built-in Module dbm (node111.html#SECTION009600000000000000000)\n8.7 Built-in Module gdbm (node112.html#SECTION009700000000000000000)\n8.8 Built-in Module termios (node113.html#SECTION009800000000000000000)\n- Example (node114.html#SECTION009810000000000000000)\n8.9 Standard Module TERMIOS (node115.html#SECTION009900000000000000000)\n8.10 Built-in Module fcntl (node116.html#SECTION0091000000000000000000)\n8.11 Standard Module posixfile (node117.html#SECTION0091100000000000000000)\n8.12 Built-in Module resource (node118.html#SECTION0091200000000000000000)\n- Resource Limits (node119.html#SECTION0091210000000000000000)\nResource Usage (node120.html#SECTION0091220000000000000000)\n8.13 Built-in Module syslog (node121.html#SECTION0091300000000000000000)\n8.14 Standard Module stat (node122.html#SECTION0091400000000000000000)\n8.15 Standard Module commands (node123.html#SECTION0091500000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1550, "url": "https://docs.python.org/1.5/lib/node105.html"} {"title": "8.1 Built-in Module posix", "text": "node107.html\nnode105.html\nnode105.html\nnode1.html\nnode270.html\n---\n# 8.1 Built-in Module posix\nThis module provides access to operating system functionality that is\nstandardized by the C Standard and the POSIX standard (a thinly disguised\nUnix interface).\nDo not import this module directly. Instead, import the\nmodule os, which provides a portable version of this\ninterface. On Unix, the os module provides a superset of\nthe posix interface. On non-Unix operating systems the\nposix module is not available, but a subset is always available\nthrough the os interface. Once os is imported, there is\nno performance penalty in using it instead of\nposix. In addition, os provides some additional\nfunctionality, such as automatically calling putenv()\nwhen an entry is 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\nfor type errors, while errors reported by the system calls raise\nposix.error, described below.\nModule posix defines the following data items:\nIt defines the following functions and constants:\n---\nnode107.html\nnode105.html\nnode105.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1318, "url": "https://docs.python.org/1.5/lib/node106.html"} {"title": "8.2 Standard Module posixpath", "text": "node108.html\nnode105.html\nnode106.html\nnode1.html\nnode270.html\n---\n# 8.2 Standard Module posixpath\nThis module implements some useful functions on POSIX pathnames.\nDo not import this module directly. Instead, import the\nmodule os and use os.path.\n---\nnode108.html\nnode105.html\nnode106.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 330, "url": "https://docs.python.org/1.5/lib/node107.html"} {"title": "8.3 Built-in Module pwd", "text": "node109.html\nnode105.html\nnode107.html\nnode1.html\nnode270.html\n---\n# 8.3 Built-in Module pwd\nThis module provides access to the Unix password database.\nIt 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:\npw_name,\npw_passwd,\npw_uid,\npw_gid,\npw_gecos,\npw_dir,\npw_shell.\nThe uid and gid items are integers, all others are strings.\nA KeyError exception is raised if the entry asked for cannot be found.\nIt defines the following items:\n---\nguido@python.org", "python_version": "1.5", "length": 573, "url": "https://docs.python.org/1.5/lib/node108.html"} {"title": "8.4 Built-in Module grp", "text": "node110.html\nnode105.html\nnode108.html\nnode1.html\nnode270.html\n---\n# 8.4 Built-in Module grp\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:\ngr_name,\ngr_passwd,\ngr_gid,\ngr_mem.\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.)\nA KeyError exception is raised if the entry asked for cannot be found.\nIt defines the following items:\n---\nguido@python.org", "python_version": "1.5", "length": 693, "url": "https://docs.python.org/1.5/lib/node109.html"} {"title": "More String Operations", "text": "node12.html\nnode10.html\nnode10.html\nnode1.html\nnode270.html\n---\n### More String Operations\nString objects have one unique built-in operation: the %\noperator (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 object.footnode.html#527\nThe following format characters are understood:\n%, c, s, i, d, u, o, 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 -, +,\nblank, # and 0 are understood. The size specifiers h, l or L may be\npresent but are ignored. The %s conversion takes any Python\nobject and converts it to a string using str() before\nformatting it. The ANSI features %p and %n\nare not supported. Since Python strings have an explicit length,\n%s conversions don't assume that '\\0' is the end of\nthe 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.footnode.html#536\nAll 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, and\neach format formats the corresponding entry from the mapping. E.g.\n```text\n>>> count = 2\n>>> language = 'Python'\n>>> print '%(language)s has %(count)03d quote types.' % vars()\nPython has 002 quote types.\n>>>\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.\n---\nguido@python.org", "python_version": "1.5", "length": 1976, "url": "https://docs.python.org/1.5/lib/node11.html"} {"title": "8.5 Built-in Module crypt", "text": "node111.html\nnode105.html\nnode109.html\nnode1.html\nnode270.html\n---\n# 8.5 Built-in Module crypt\nThis module implements an interface to the crypt(3) routine,\nwhich is a one-way hash function based upon a modified DES algorithm;\nsee the 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.\nThe module and documentation were written by Steve Majewski.\n---\nguido@python.org", "python_version": "1.5", "length": 494, "url": "https://docs.python.org/1.5/lib/node110.html"} {"title": "8.6 Built-in Module dbm", "text": "node112.html\nnode105.html\nnode110.html\nnode1.html\nnode270.html\n---\n# 8.6 Built-in Module dbm\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, which provides a similar interface\nusing the GNU GDBM library.\nThe module defines the following constant and functions:\n---\nguido@python.org", "python_version": "1.5", "length": 534, "url": "https://docs.python.org/1.5/lib/node111.html"} {"title": "8.7 Built-in Module gdbm", "text": "node113.html\nnode105.html\nnode111.html\nnode1.html\nnode270.html\n---\n# 8.7 Built-in Module gdbm\nThis module is quite similar to the dbm module, but uses gdbm\ninstead to provide some additional functionality. Please note that\nthe file formats created by 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 the\nitems() 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:\n---\nnode113.html\nnode105.html\nnode111.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 781, "url": "https://docs.python.org/1.5/lib/node112.html"} {"title": "8.8 Built-in Module termios", "text": "node114.html\nnode105.html\nnode112.html\nnode1.html\nnode270.html\n---\n# 8.8 Built-in Module termios\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 TERMIOS\nmodule, which defines the relevant symbolic constants (see the next\nsection).\nThe module defines the following functions:\n---\n- Example (node114.html#SECTION009810000000000000000)\n---\nnode114.html\nnode105.html\nnode112.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 879, "url": "https://docs.python.org/1.5/lib/node113.html"} {"title": "Example", "text": "node115.html\nnode113.html\nnode113.html\nnode1.html\nnode270.html\n---\n## Example\nHere's a function that prompts for a password with echoing turned off.\nNote the technique using a separate termios.tcgetattr() call\nand a try ... finally statement to ensure that the old tty\nattributes are restored exactly no matter what happens:\n```text\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```\n---\nguido@python.org", "python_version": "1.5", "length": 691, "url": "https://docs.python.org/1.5/lib/node114.html"} {"title": "8.9 Standard Module TERMIOS", "text": "node116.html\nnode105.html\nnode114.html\nnode1.html\nnode270.html\n---\n# 8.9 Standard Module TERMIOS\nThis module defines the symbolic constants required to use the\ntermios module (see the previous section). See the POSIX or\nUnix manual pages (or the source) for a list of those constants.\nNote: this module resides in a system-dependent subdirectory of the\nPython library directory. You may have to generate it for your\nparticular system using the script `Tools/scripts/h2py.py'.\n---\nguido@python.org", "python_version": "1.5", "length": 496, "url": "https://docs.python.org/1.5/lib/node115.html"} {"title": "8.10 Built-in Module fcntl", "text": "node117.html\nnode105.html\nnode115.html\nnode1.html\nnode270.html\n---\n# 8.10 Built-in Module fcntl\nThis module performs file control and I/O control on file descriptors.\nIt is an interface to the fcntl() and ioctl() Unix routines.\nFile descriptors can be obtained with the fileno() method of a\nfile or socket object.\nThe module defines the following functions:\nIf the library modules FCNTL or IOCTL are missing, you\ncan find the opcodes in the C include files `sys/fcntl.h' and\n`sys/ioctl.h'. You can create the modules yourself with the h2py\nscript, found in the `Tools/scripts' directory.\nExamples (all on a SVR4 compliant system):\n```text\nimport struct, 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(file.fileno(), FCNTL.F_SETLKW, lockdata)\n```\nNote that in the first example the return value variable rv will\nhold an integer value; in the second example it will hold a string\nvalue. The structure lay-out for the lockadata variable is\nsystem dependent - therefore using the flock() call may be\nbetter.\n---\nnode117.html\nnode105.html\nnode115.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1184, "url": "https://docs.python.org/1.5/lib/node116.html"} {"title": "8.11 Standard Module posixfile", "text": "node118.html\nnode105.html\nnode116.html\nnode1.html\nnode270.html\n---\n# 8.11 Standard Module posixfile\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() for file locking.\nTo instantiate a posixfile object, use the open() function in\nthe posixfile module. The resulting object looks and feels roughly\nthe 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 return IOError when the request fails.\nFormat characters for the lock() method have the following meaning:\nFormat | Meaning\nIn addition the following modifiers can be added to the format:\nModifier | Meaning | Notes\nNote:\n(1) The lock returned is in the format (mode, len, start,\nwhence, pid) where mode is a character representing the type of lock\n('r' or 'w'). This modifier prevents a request from being granted; it\nis for query purposes only.\nFormat character for the flags() method have the following meaning:\nFormat | Meaning\nIn addition the following modifiers can be added to the format:\nModifier | Meaning | Notes\nNote:\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:\n```text\nfrom posixfile import *\n\nfile = open('/tmp/test', 'w')\nfile.lock('w|')\n...\nfile.lock('u')\nfile.close()\n```\n---\nnode118.html\nnode105.html\nnode116.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2024, "url": "https://docs.python.org/1.5/lib/node117.html"} {"title": "8.12 Built-in Module resource", "text": "node119.html\nnode105.html\nnode117.html\nnode1.html\nnode270.html\n---\n# 8.12 Built-in Module resource\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:\n---\n- Resource Limits (node119.html#SECTION0091210000000000000000)\nResource Usage (node120.html#SECTION0091220000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 546, "url": "https://docs.python.org/1.5/lib/node118.html"} {"title": "Resource Limits", "text": "node120.html\nnode118.html\nnode118.html\nnode1.html\nnode270.html\n---\n## 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() 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 defined\nbelow. The values of these symbols are exactly the constants used\nby C programs.\nThe Unix man page for getrlimit() lists the available\nresources. Note that not all systems use the same symbol or same\nvalue to denote the same resource.\n---\nnode120.html\nnode118.html\nnode118.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1324, "url": "https://docs.python.org/1.5/lib/node119.html"} {"title": "Mutable Sequence Types", "text": "node13.html\nnode10.html\nnode11.html\nnode1.html\nnode270.html\n---\n### 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):\nOperation | Result | Notes\n,\nNotes:\n---\nnode13.html\nnode10.html\nnode11.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 599, "url": "https://docs.python.org/1.5/lib/node12.html"} {"title": "Resource Usage", "text": "node121.html\nnode118.html\nnode119.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode121.html\nnode118.html\nnode119.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 366, "url": "https://docs.python.org/1.5/lib/node120.html"} {"title": "8.13 Built-in Module syslog", "text": "node122.html\nnode105.html\nnode120.html\nnode1.html\nnode270.html\n---\n# 8.13 Built-in Module syslog\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:\n---\nguido@python.org", "python_version": "1.5", "length": 358, "url": "https://docs.python.org/1.5/lib/node121.html"} {"title": "8.14 Standard Module stat", "text": "node123.html\nnode105.html\nnode121.html\nnode1.html\nnode270.html\n---\n# 8.14 Standard Module stat\nThe stat module defines constants and functions for interpreting the\nresults of os.stat() and os.lstat() (if they exist).\nFor complete details about the stat() and lstat() system\ncalls, consult your local man pages.\nThe stat module defines the following functions:\nAll the data items below are simply symbolic indexes into the 10-tuple\nreturned by os.stat() or os.lstat().\nExample:\n```text\nimport os, sys\nfrom stat import *\n\ndef process(dir, func):\n'''recursively descend the directory rooted at dir, calling func for\neach regular file'''\n\nfor f in os.listdir(dir):\nmode = os.stat('%s/%s' % (dir, f))[ST_MODE]\nif S_ISDIR(mode):\n# recurse into directory\nprocess('%s/%s' % (dir, f), func)\nelif S_ISREG(mode):\nfunc('%s/%s' % (dir, f))\nelse:\nprint 'Skipping %s/%s' % (dir, f)\n\ndef f(file):\nprint 'frobbed', file\n\nif __name__ == '__main__': process(sys.argv[1], f)\n```\n---\nguido@python.org", "python_version": "1.5", "length": 979, "url": "https://docs.python.org/1.5/lib/node122.html"} {"title": "8.15 Standard Module commands", "text": "node124.html\nnode105.html\nnode122.html\nnode1.html\nnode270.html\n---\n# 8.15 Standard Module commands\nThe commands module contains wrapper functions for os.popen()\nwhich take a system command as a string and return any output generated by\nthe command and, optionally, the exit status.\nThe commands module is only usable on systems which support\npopen() (currently Unix).\nThe commands module defines the following functions:\nExample:\n```text\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```\n---\nguido@python.org", "python_version": "1.5", "length": 840, "url": "https://docs.python.org/1.5/lib/node123.html"} {"title": "9 The Python Debugger", "text": "node125.html\nlib.html\nnode123.html\nnode1.html\nnode270.html\n---\n# 9 The Python Debugger\nThe module pdb defines an interactive source code debugger for\nPython programs. It supports setting\n(conditional) breakpoints and single stepping\nat the source line level, inspection of stack frames, source code\nlisting, and evaluation of arbitrary Python code in the context of any\nstack frame. It also supports post-mortem debugging and can be called\nunder program control.\nThe debugger is extensible -- it is actually defined as a class\nPdb. This is currently undocumented but easily understood by\nreading the source. The extension interface uses the (also\nundocumented) modules bdb and cmd.\nA primitive windowing version of the debugger also exists -- this is\nmodule wdb, which requires STDWIN (see the chapter on STDWIN\nspecific modules).\nThe debugger's prompt is ``(Pdb) ''.\nTypical usage to run a program under control of the debugger is:\n```text\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:\npython /usr/local/lib/python1.4/pdb.py myscript.py\nTypical usage to inspect a crashed program is:\n```text\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:\n---\n- 9.1 Debugger Commands (node125.html#SECTION0010100000000000000000)\n9.2 How It Works (node126.html#SECTION0010200000000000000000)\n---\nnode125.html\nlib.html\nnode123.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1897, "url": "https://docs.python.org/1.5/lib/node124.html"} {"title": "9.1 Debugger Commands", "text": "node126.html\nnode124.html\nnode124.html\nnode1.html\nnode270.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.\n---\nnode126.html\nnode124.html\nnode124.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1299, "url": "https://docs.python.org/1.5/lib/node125.html"} {"title": "9.2 How It Works", "text": "node127.html\nnode124.html\nnode125.html\nnode1.html\nnode270.html\n---\n# 9.2 How It Works\nSome changes were made to the interpreter:\n- sys.settrace(func) sets the global trace functionthere can also a local trace function (see later)\nTrace functions have three arguments: (frame, event, arg)\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\nNone 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:\nNote that as an exception is propagated down the chain of callers, an\n'exception' event is generated at each level.\nStack frame objects have the following read-only attributes:\nCode objects have the following read-only attributes:\n---\nnode127.html\nnode124.html\nnode125.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1099, "url": "https://docs.python.org/1.5/lib/node126.html"} {"title": "10 The Python Profiler", "text": "node128.html\nlib.html\nnode126.html\nnode1.html\nnode270.html\n---\n# 10 The Python Profiler\nCopyright © 1994, by InfoSeek Corporation, all rights reserved.\nWritten by James Roskindfootnode.html#8942\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- 10.1 Introduction to the profiler (node128.html#SECTION0011100000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node129.html#SECTION0011200000000000000000)\n10.3 Instant Users Manual (node130.html#SECTION0011300000000000000000)\n10.4 What Is Deterministic Profiling? (node131.html#SECTION0011400000000000000000)\n10.5 Reference Manual (node132.html#SECTION0011500000000000000000)\n- The Stats Class (node133.html#SECTION0011510000000000000000)\n10.6 Limitations (node134.html#SECTION0011600000000000000000)\n10.7 Calibration (node135.html#SECTION0011700000000000000000)\n10.8 Extensions - Deriving Better Profilers (node136.html#SECTION0011800000000000000000)\n- OldProfile Class (node137.html#SECTION0011810000000000000000)\nHotProfile Class (node138.html#SECTION0011820000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2747, "url": "https://docs.python.org/1.5/lib/node127.html"} {"title": "10.1 Introduction to the profiler", "text": "node129.html\nnode127.html\nnode127.html\nnode1.html\nnode270.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.\n---\nguido@python.org", "python_version": "1.5", "length": 530, "url": "https://docs.python.org/1.5/lib/node128.html"} {"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "node130.html\nnode127.html\nnode128.html\nnode1.html\nnode270.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:\n---\nguido@python.org", "python_version": "1.5", "length": 417, "url": "https://docs.python.org/1.5/lib/node129.html"} {"title": "Mapping Types", "text": "node14.html\nnode4.html\nnode12.html\nnode1.html\nnode270.html\n---\n## 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\n1.0) then they can be used interchangeably to index the same\ndictionary entry.\nDictionaries are created by placing a comma-separated list of\nkey:,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 is a\nmapping, k is a key and x is an arbitrary object):\nOperation | Result | Notes\n,\nNotes:\n---\nnode14.html\nnode4.html\nnode12.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1074, "url": "https://docs.python.org/1.5/lib/node13.html"} {"title": "10.3 Instant Users Manual", "text": "node131.html\nnode127.html\nnode129.html\nnode1.html\nnode270.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\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\nimport profile\nprofile.run(\"foo()\", 'fooprof')\n```\nprofile.py can also be invoked as\na script to profile another script. For example:\npython /usr/local/lib/python1.4/profile.py myscript.py\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\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\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\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\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\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\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\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\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\np.print_callees()\np.add('fooprof')\n```\n---\nnode131.html\nnode127.html\nnode129.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3680, "url": "https://docs.python.org/1.5/lib/node130.html"} {"title": "10.4 What Is Deterministic Profiling?", "text": "node132.html\nnode127.html\nnode130.html\nnode1.html\nnode270.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.\n---\nguido@python.org", "python_version": "1.5", "length": 1805, "url": "https://docs.python.org/1.5/lib/node131.html"} {"title": "10.5 Reference Manual", "text": "node133.html\nnode127.html\nnode131.html\nnode1.html\nnode270.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.\n---\n- The Stats Class (node133.html#SECTION0011510000000000000000)\n---\nnode133.html\nnode127.html\nnode131.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 782, "url": "https://docs.python.org/1.5/lib/node132.html"} {"title": "The Stats Class", "text": "node134.html\nnode132.html\nnode132.html\nnode1.html\nnode270.html\n---\n## The Stats Class\n---\nnode134.html\nnode132.html\nnode132.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 169, "url": "https://docs.python.org/1.5/lib/node133.html"} {"title": "10.6 Limitations", "text": "node135.html\nnode127.html\nnode133.html\nnode1.html\nnode270.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 builtin 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.\n---\nnode135.html\nnode127.html\nnode133.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2332, "url": "https://docs.python.org/1.5/lib/node134.html"} {"title": "10.7 Calibration", "text": "node136.html\nnode127.html\nnode134.html\nnode1.html\nnode270.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\nimport profile\npr = profile.Profile()\npr.calibrate(100)\npr.calibrate(100)\npr.calibrate(100)\n```\nThe argument to calibrate() is the number of times to try to do the\nsample calls to get the CPU times. If your computer is very\nfast, you might have to do:\n```text\npr.calibrate(1000)\n```\nor even:\n```text\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\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\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'\nwas 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.\n---\nnode136.html\nnode127.html\nnode134.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2371, "url": "https://docs.python.org/1.5/lib/node135.html"} {"title": "10.8 Extensions - Deriving Better Profilers", "text": "node137.html\nnode127.html\nnode135.html\nnode1.html\nnode270.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\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 pretty bad, 'cause\nit returns a tuple of floating point values, so all arithmetic is\nfloating point in the profiler!). If you want to substitute a\nbetter timer in the cleanest fashion, you should derive a class, and\nsimply put in the replacement dispatch method that better handles your\ntimer call, along with the appropriate calibration constant :-).\n---\n- OldProfile Class (node137.html#SECTION0011810000000000000000)\nHotProfile Class (node138.html#SECTION0011820000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1907, "url": "https://docs.python.org/1.5/lib/node136.html"} {"title": "OldProfile Class", "text": "node138.html\nnode136.html\nnode136.html\nnode1.html\nnode270.html\n---\n## 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\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```\n---\nguido@python.org", "python_version": "1.5", "length": 1762, "url": "https://docs.python.org/1.5/lib/node137.html"} {"title": "HotProfile Class", "text": "node139.html\nnode136.html\nnode137.html\nnode1.html\nnode270.html\n---\n## 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\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```\n---\nguido@python.org", "python_version": "1.5", "length": 1301, "url": "https://docs.python.org/1.5/lib/node138.html"} {"title": "11 Internet and WWW Services", "text": "node140.html\nlib.html\nnode138.html\nnode1.html\nnode270.html\n---\n# 11 Internet and WWW Services\nThe modules described in this chapter provide various services to\nWorld-Wide Web (WWW) clients and/or services, and a few modules\nrelated to news and email. They are all implemented in Python. Some\nof these modules require the presence of the system-dependent module\nsockets, which is currently only fully\nsupported on Unix and Windows NT. Here is an overview:\n---\n- 11.1 Standard Module cgi (node140.html#SECTION0012100000000000000000)\n- Introduction (node141.html#SECTION0012110000000000000000)\nUsing the cgi module (node142.html#SECTION0012120000000000000000)\nOld classes (node143.html#SECTION0012130000000000000000)\nFunctions (node144.html#SECTION0012140000000000000000)\nCaring about security (node145.html#SECTION0012150000000000000000)\nInstalling your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)\nTesting your CGI script (node147.html#SECTION0012170000000000000000)\nDebugging CGI scripts (node148.html#SECTION0012180000000000000000)\nCommon problems and solutions (node149.html#SECTION0012190000000000000000)\n11.2 Standard Module urllib (node150.html#SECTION0012200000000000000000)\n11.3 Standard Module httplib (node151.html#SECTION0012300000000000000000)\n- HTTP Objects (node152.html#SECTION0012310000000000000000)\nExample (node153.html#SECTION0012320000000000000000)\n11.4 Standard Module ftplib (node154.html#SECTION0012400000000000000000)\n- FTP Objects (node155.html#SECTION0012410000000000000000)\n11.5 Standard Module gopherlib (node156.html#SECTION0012500000000000000000)\n11.6 Standard Module nntplib (node157.html#SECTION0012600000000000000000)\n- NNTP Objects (node158.html#SECTION0012610000000000000000)\n11.7 Standard Module urlparse (node159.html#SECTION0012700000000000000000)\n11.8 Standard Module sgmllib (node160.html#SECTION0012800000000000000000)\n11.9 Standard Module htmllib (node161.html#SECTION0012900000000000000000)\n11.10 Standard Module xmllib (node162.html#SECTION00121000000000000000000)\n11.11 Standard Module formatter (node163.html#SECTION00121100000000000000000)\n- The Formatter Interface (node164.html#SECTION00121110000000000000000)\nFormatter Implementations (node165.html#SECTION00121120000000000000000)\nThe Writer Interface (node166.html#SECTION00121130000000000000000)\nWriter Implementations (node167.html#SECTION00121140000000000000000)\n11.12 Standard Module rfc822 (node168.html#SECTION00121200000000000000000)\n- Message Objects (node169.html#SECTION00121210000000000000000)\n11.13 Standard Module mimetools (node170.html#SECTION00121300000000000000000)\n- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)\n11.14 Standard Module binhex (node172.html#SECTION00121400000000000000000)\n- Notes (node173.html#SECTION00121410000000000000000)\n11.15 Standard Module uu (node174.html#SECTION00121500000000000000000)\n11.16 Built-in Module binascii (node175.html#SECTION00121600000000000000000)\n11.17 Standard Module xdrlib (node176.html#SECTION00121700000000000000000)\n- Packer Objects (node177.html#SECTION00121710000000000000000)\nUnpacker Objects (node178.html#SECTION00121720000000000000000)\nExceptions (node179.html#SECTION00121730000000000000000)\n11.18 Standard Module mailcap (node180.html#SECTION00121800000000000000000)\n11.19 Standard Module base64 (node181.html#SECTION00121900000000000000000)\n11.20 Standard Module quopri (node182.html#SECTION00122000000000000000000)\n11.21 Standard Module SocketServer (node183.html#SECTION00122100000000000000000)\n11.22 Standard Module mailbox (node184.html#SECTION00122200000000000000000)\n- Mailbox Objects (node185.html#SECTION00122210000000000000000)\n11.23 Standard Module mimify (node186.html#SECTION00122300000000000000000)\n11.24 Standard Module BaseHTTPServer (node187.html#SECTION00122400000000000000000)\n---\nnode140.html\nlib.html\nnode138.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3916, "url": "https://docs.python.org/1.5/lib/node139.html"} {"title": "Other Built-in Types", "text": "node15.html\nnode4.html\nnode13.html\nnode1.html\nnode270.html\n---\n## Other Built-in Types\nThe interpreter supports several other kinds of objects.\nMost of these support only one or two operations.\n---\n- Modules (node15.html#SECTION003171000000000000000)\nClasses and Class Instances (node16.html#SECTION003172000000000000000)\nFunctions (node17.html#SECTION003173000000000000000)\nMethods (node18.html#SECTION003174000000000000000)\nCode Objects (node19.html#SECTION003175000000000000000)\nType Objects (node20.html#SECTION003176000000000000000)\nThe Null Object (node21.html#SECTION003177000000000000000)\nFile Objects (node22.html#SECTION003178000000000000000)\nInternal Objects (node23.html#SECTION003179000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 733, "url": "https://docs.python.org/1.5/lib/node14.html"} {"title": "11.1 Standard Module cgi", "text": "node141.html\nnode139.html\nnode139.html\nnode1.html\nnode270.html\n---\n# 11.1 Standard Module cgi\nSupport module for CGI (Common Gateway Interface) scripts.\nThis module defines a number of utilities for use by CGI scripts\nwritten in Python.\n---\n- Introduction (node141.html#SECTION0012110000000000000000)\nUsing the cgi module (node142.html#SECTION0012120000000000000000)\nOld classes (node143.html#SECTION0012130000000000000000)\nFunctions (node144.html#SECTION0012140000000000000000)\nCaring about security (node145.html#SECTION0012150000000000000000)\nInstalling your CGI script on a Unix system (node146.html#SECTION0012160000000000000000)\nTesting your CGI script (node147.html#SECTION0012170000000000000000)\nDebugging CGI scripts (node148.html#SECTION0012180000000000000000)\nCommon problems and solutions (node149.html#SECTION0012190000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 866, "url": "https://docs.python.org/1.5/lib/node140.html"} {"title": "Introduction", "text": "node142.html\nnode140.html\nnode140.html\nnode1.html\nnode270.html\n---\n## 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 (`cgi.py') 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\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\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.)\n---\nguido@python.org", "python_version": "1.5", "length": 1845, "url": "https://docs.python.org/1.5/lib/node141.html"} {"title": "Using the cgi module", "text": "node143.html\nnode140.html\nnode141.html\nnode1.html\nnode270.html\n---\n## Using the cgi module\nBegin by writing import cgi. Don't use from cgi import * - the\nmodule defines all sorts of names for its own use or for backward\ncompatibility that you don't want in your namespace.\nIt's best to use the FieldStorage class. The other classes define in this\nmodule are provided mostly for backward compatibility. Instantiate it\nexactly once, without arguments. This reads the form contents from\nstandard input or the environment (depending on the value of various\nenvironment variables set according to the CGI standard). Since it may\nconsume standard input, it should be instantiated only once.\nThe FieldStorage instance can be accessed as if it were a Python\ndictionary. For instance, the following code (which assumes that the\nContent-type header and blank line have already been printed) checks that\nthe fields name and addr are both set to a non-empty string:\n```text\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 themselves instances\nof FieldStorage (or MiniFieldStorage, 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 (Mini)FieldStorage\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 have a single\ninstance or a list of instances. For example, here's code that\nconcatenates any number of username fields, separated by commas:\n```text\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. You can\ntest for an uploaded file by testing either the filename attribute or the\nfile attribute. You can then read the data at leasure from the file\nattribute:\n```text\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 multipart/*\nencoding). When this occurs, the item will be a dictionary-like\nFieldStorage item. This can be determined by testing its type\nattribute, which should have the value multipart/form-data (or\nperhaps another string beginning with multipart/ It this case, it\ncan be iterated over recursively just like the top-level form object.\nWhen a form is submitted in the ``old'' format (as the query string or as a\nsingle data part of type application/x-www-form-urlencoded), the items\nwill actually be instances of the class MiniFieldStorage. In this case,\nthe list, file and filename attributes are always None.\n---\nnode143.html\nnode140.html\nnode141.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3533, "url": "https://docs.python.org/1.5/lib/node142.html"} {"title": "Old classes", "text": "node144.html\nnode140.html\nnode142.html\nnode1.html\nnode270.html\n---\n## Old classes\nThese classes, present in earlier versions of the cgi module, are still\nsupported for backward compatibility. New applications should use the\nFieldStorage class.\nSvFormContentDict\nsingle value form content as dictionary; assumes each\nfield name occurs in the form only once.\nFormContentDict\nmultiple value form content as dictionary (the form\nitems are lists of values). Useful if your form contains multiple\nfields with the same name.\nOther classes (FormContent, InterpFormContentDict) are present for\nbackwards compatibility with really old applications only. If you still\nuse these and would be inconvenienced when they disappeared from a next\nversion of this module, drop me a note.\n---\nguido@python.org", "python_version": "1.5", "length": 789, "url": "https://docs.python.org/1.5/lib/node143.html"} {"title": "Functions", "text": "node145.html\nnode140.html\nnode143.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode145.html\nnode140.html\nnode143.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 305, "url": "https://docs.python.org/1.5/lib/node144.html"} {"title": "Caring about security", "text": "node146.html\nnode140.html\nnode144.html\nnode1.html\nnode270.html\n---\n## Caring about security\nThere's one important rule: if you invoke an external program (e.g.\nvia the os.system() or os.popen() functions), make very sure you don't\npass arbitrary strings received from the client to the shell. This is\na well-known security hole whereby clever hackers anywhere on the web\ncan exploit a gullible CGI script to invoke arbitrary shell commands.\nEven parts of the URL or field names cannot be trusted, since the\nrequest doesn't have to come from your form!\nTo be on the safe side, if you must pass a string gotten from a form\nto a shell command, you should make sure the string contains only\nalphanumeric characters, dashes, underscores, and periods.\n---\nguido@python.org", "python_version": "1.5", "length": 766, "url": "https://docs.python.org/1.5/lib/node145.html"} {"title": "Installing your CGI script on a Unix system", "text": "node147.html\nnode140.html\nnode145.html\nnode1.html\nnode270.html\n---\n## 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 755 (use chmod 755 filename). Make sure\nthat the first line of the script contains #! starting in column 1\nfollowed by the pathname of the Python interpreter, for instance:\n```text\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 should\nbe 644 for readable and 666 for writable. This is because, for\nsecurity reasons, the HTTP server executes your script as user\n``nobody'', without any special privileges. It can only read (write,\nexecute) files that everybody can read (write, execute). The current\ndirectory at execution time is also different (it is usually the\nserver's cgi-bin directory) and the set of environment variables is\nalso different from what you get at login. in particular, don't count\non the shell's search path for executables ($PATH) or the Python\nmodule search path ($PYTHONPATH) to be set to anything 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\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).\n---\nguido@python.org", "python_version": "1.5", "length": 1948, "url": "https://docs.python.org/1.5/lib/node146.html"} {"title": "Testing your CGI script", "text": "node148.html\nnode140.html\nnode146.html\nnode1.html\nnode270.html\n---\n## 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:\n---\nguido@python.org", "python_version": "1.5", "length": 654, "url": "https://docs.python.org/1.5/lib/node147.html"} {"title": "Debugging CGI scripts", "text": "node149.html\nnode140.html\nnode147.html\nnode1.html\nnode270.html\n---\n## 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\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 test()\nfunction from your script: replace its main code with the single\nstatement\n```text\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\n*some* code, it is easy to catch exceptions and cause a traceback to\nbe printed. The test() function below in this module is an example.\nHere are the rules:\n1. Import the traceback module (before entering the\ntry-except!)Make sure you finish printing the headers and the blank\nline earlyAssign sys.stderr to sys.stdoutWrap all remaining code in a try-except statementIn the except clause, call traceback.print_exc()\nFor example:\n```text\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 traceback\nprints 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\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.\n---\nnode149.html\nnode140.html\nnode147.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3587, "url": "https://docs.python.org/1.5/lib/node148.html"}
{"title": "Common problems and solutions", "text": "node150.html\nnode140.html\nnode148.html\nnode1.html\nnode270.html\n---\n## Common problems and solutions\n- Most HTTP servers buffer the output from CGI scripts until the\nscript is completed. This means that it is not possible to display a\nprogress report on the client's display while the script is running.Check the installation instructions above.Check the HTTP server's log files. (tail -f logfile in a separate\nwindow may be useful!)Always check a script for syntax errors first, by doing something\nlike python script.py.When using any of the debugging techniques, don't forget to add\nimport sys to the top of the script.When invoking external programs, make sure they can be found.\nUsually, this means using absolute path names - $PATH is usually not\nset to a very useful value in a CGI script.When reading or writing external files, make sure they can be read\nor written by every user on the system.Don't try to give a CGI script a set-uid mode. This doesn't work on\nmost systems, and is a security liability as well.\n---\nguido@python.org", "python_version": "1.5", "length": 1039, "url": "https://docs.python.org/1.5/lib/node149.html"}
{"title": "Modules", "text": "node16.html\nnode14.html\nnode14.html\nnode1.html\nnode270.html\n---\n### Modules\nThe only special operation on a module is attribute access:\nm.name, where m is a module and name accesses\na name defined in m's symbol table. Module attributes can be\nassigned to. (Note that the import statement is not, strictly\nspoken, an operation on a module object; import foo does not\nrequire a module object named foo to exist, rather it requires\nan (external) definition for a module named foo\nsomewhere.)\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 m.__dict__ = {}.\nModules are written like this: .\n---\nguido@python.org", "python_version": "1.5", "length": 907, "url": "https://docs.python.org/1.5/lib/node15.html"}
{"title": "11.2 Standard Module urllib", "text": "node151.html\nnode139.html\nnode149.html\nnode1.html\nnode270.html\n---\n# 11.2 Standard Module urllib\nThis module provides a high-level interface for fetching data across\nthe World-Wide Web. In particular, the urlopen() function is\nsimilar to the built-in function open(), but accepts URLs\n(Universal Resource Locators) instead of filenames. Some restrictions\napply -- it can only open URLs for reading, and no seek operations\nare available.\nIt defines the following public functions:\nRestrictions:\n- Currently, only the following protocols are supported: HTTP, (versions\n0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.\nThe caching feature of urlretrieve() has been disabled until I\nfind the time to hack proper processing of Expiration time headers.There should be a function to query whether a particular URL is in\nthe cache.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.The urlopen() and urlretrieve() functions can cause\narbitrarily long delays while waiting for a network connection to be\nset up. This means that it is difficult to build an interactive\nweb client using these functions without using threads.The data returned by urlopen() or urlretrieve() is the\nraw data returned by the server. This may be binary data (e.g. an\nimage), plain text or (for example) HTML. The HTTP protocol provides\ntype information in the reply header, which can be inspected by\nlooking at the Content-type header. For the Gopher protocol,\ntype information is encoded in the URL; there is currently no easy way\nto extract it. If the returned data is HTML, you can use the module\nhtmllib to parse it.\nAlthough the urllib module contains (undocumented) routines to\nparse and unparse URL strings, the recommended interface for URL\nmanipulation is in module urlparse.\n---\nnode151.html\nnode139.html\nnode149.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1999, "url": "https://docs.python.org/1.5/lib/node150.html"}
{"title": "11.3 Standard Module httplib", "text": "node152.html\nnode139.html\nnode150.html\nnode1.html\nnode270.html\n---\n# 11.3 Standard Module httplib\nThis module defines a class which implements the client side of the\nHTTP protocol. It is normally not used directly -- the module\nurllib uses it to handle URLs that use HTTP.\nThe module defines one class, HTTP. An HTTP instance\nrepresents one transaction with an HTTP server. It should be\ninstantiated passing it a host and optional port number. If no port\nnumber is passed, the port is extracted from the host string if it has\nthe form host:port, else the default HTTP port (80) is used.\nIf no host is passed, no connection is made, and the connect\nmethod should be used to connect to a server. For example, the\nfollowing calls all create instances that connect to the server at the\nsame host and port:\n```text\n>>> h1 = httplib.HTTP('www.cwi.nl')\n>>> h2 = httplib.HTTP('www.cwi.nl:80')\n>>> h3 = httplib.HTTP('www.cwi.nl', 80)\n```\nOnce an HTTP instance has been connected to an HTTP server, it\nshould be used as follows:\n---\n- HTTP Objects (node152.html#SECTION0012310000000000000000)\nExample (node153.html#SECTION0012320000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1156, "url": "https://docs.python.org/1.5/lib/node151.html"}
{"title": "HTTP Objects", "text": "node153.html\nnode151.html\nnode151.html\nnode1.html\nnode270.html\n---\n## HTTP Objects\nHTTP instances have the following methods:\n---\nnode153.html\nnode151.html\nnode151.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 209, "url": "https://docs.python.org/1.5/lib/node152.html"}
{"title": "Example", "text": "node154.html\nnode151.html\nnode152.html\nnode1.html\nnode270.html\n---\n## Example\nHere is an example session:\n```text\n>>> import httplib\n>>> h = httplib.HTTP('www.cwi.nl')\n>>> h.putrequest('GET', '/index.html')\n>>> h.putheader('Accept', 'text/html')\n>>> h.putheader('Accept', 'text/plain')\n>>> h.endheaders()\n>>> errcode, errmsg, headers = h.getreply()\n>>> print errcode # Should be 200\n>>> f = h.getfile()\n>>> data = f.read() # Get the raw HTML\n>>> f.close()\n>>>\n```\n---\nguido@python.org", "python_version": "1.5", "length": 484, "url": "https://docs.python.org/1.5/lib/node153.html"}
{"title": "11.4 Standard Module ftplib", "text": "node155.html\nnode139.html\nnode153.html\nnode1.html\nnode270.html\n---\n# 11.4 Standard Module ftplib\nThis module defines the class FTP and a few related items. The\nFTP class implements the client side of the FTP protocol. You\ncan use this to write Python programs that perform a variety of\nautomated FTP jobs, such as mirroring other ftp servers. It is also\nused by the module urllib to handle URLs that use FTP. For\nmore information on FTP (File Transfer Protocol), see Internet RFC 959.\nHere's a sample session using the ftplib module:\n```text\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.quit()\n```\nThe module defines the following items:\n---\n- FTP Objects (node155.html#SECTION0012410000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1050, "url": "https://docs.python.org/1.5/lib/node154.html"}
{"title": "FTP Objects", "text": "node156.html\nnode154.html\nnode154.html\nnode1.html\nnode270.html\n---\n## FTP Objects\nFTP instances have the following methods:\n---\nnode156.html\nnode154.html\nnode154.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 207, "url": "https://docs.python.org/1.5/lib/node155.html"}
{"title": "11.5 Standard Module gopherlib", "text": "node157.html\nnode139.html\nnode155.html\nnode1.html\nnode270.html\n---\n# 11.5 Standard Module gopherlib\nThis module provides a minimal implementation of client side of the\nthe Gopher protocol. It is used by the module urllib to handle\nURLs that use the Gopher protocol.\nThe module defines the following functions:\nNote that the data returned by the Gopher server can be of any type,\ndepending on the first character of the selector string. If the data\nis text (first character of the selector is `0'), lines are\nterminated by CRLF, and the data is terminated by a line consisting of\na single `.', and a leading `.' should be stripped from\nlines that begin with `..'. Directory listings (first character\nof the selector is `1') are transferred using the same protocol.\n---\nguido@python.org", "python_version": "1.5", "length": 784, "url": "https://docs.python.org/1.5/lib/node156.html"}
{"title": "11.6 Standard Module nntplib", "text": "node158.html\nnode139.html\nnode156.html\nnode1.html\nnode270.html\n---\n# 11.6 Standard Module nntplib\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.\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>>> 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>>>\n```\nTo post an article from a file (this assumes that the article has\nvalid headers):\n```text\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>>>\n```\nThe module itself defines the following items:\n---\n- NNTP Objects (node158.html#SECTION0012610000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1734, "url": "https://docs.python.org/1.5/lib/node157.html"}
{"title": "NNTP Objects", "text": "node159.html\nnode157.html\nnode157.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode159.html\nnode157.html\nnode157.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 461, "url": "https://docs.python.org/1.5/lib/node158.html"}
{"title": "11.7 Standard Module urlparse", "text": "node160.html\nnode139.html\nnode158.html\nnode1.html\nnode270.html\n---\n# 11.7 Standard Module urlparse\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 for details on relative\nURLs and RFC 1738 for information on basic URL syntax.\nIt defines the following functions:\n---\nnode160.html\nnode139.html\nnode158.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 706, "url": "https://docs.python.org/1.5/lib/node159.html"}
{"title": "Classes and Class Instances", "text": "node17.html\nnode14.html\nnode15.html\nnode1.html\nnode270.html\n---\n### Classes and Class Instances\nSee Chapters 3 and 7 of the Python Reference Manual for these.\n---\nguido@python.org", "python_version": "1.5", "length": 179, "url": "https://docs.python.org/1.5/lib/node16.html"}
{"title": "11.8 Standard Module sgmllib", "text": "node161.html\nnode139.html\nnode159.html\nnode1.html\nnode270.html\n---\n# 11.8 Standard Module sgmllib\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.\nIn particular, the parser is hardcoded to recognize the following\nconstructs:\n- Opening and closing tags of the form\n`' and\n`', respectively.Numeric character references of the form `&#name;'.Entity references of the form `&name;'.SGML comments of the form `'. Note that\nspaces, tabs, and newlines are allowed between the trailing\n`>' and the immediately preceeding `-'.\nThe SGMLParser class must be instantiated without arguments.\nIt has 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:\nNote that the parser maintains a stack of open elements for which no\nend tag has been found yet. Only tags processed by\nstart_tag() are pushed on this stack. Definition of an\nend_tag() method is optional for these tags. For tags\nprocessed by do_tag() or by unknown_tag(), no\nend_tag() method must be defined; if defined, it will not\nbe used. If both start_tag() and do_tag()\nmethods exist for a tag, the start_tag() method takes\nprecedence.\n---\nnode161.html\nnode139.html\nnode159.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1712, "url": "https://docs.python.org/1.5/lib/node160.html"}
{"title": "11.9 Standard Module htmllib", "text": "node162.html\nnode139.html\nnode160.html\nnode1.html\nnode270.html\n---\n# 11.9 Standard Module htmllib\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. The HTMLParser\nimplementation supports the HTML 2.0 language as described in\nRFC 1866. Two implementations of formatter objects are provided in\nthe formatter 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\nparser.feed(open('myfile.html').read())\nparser.close()\n```\nThe 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 is encountered; end_tag() is called\nwhen a closing tag of the form  is encountered. If\nan opening tag requires a corresponding closing tag, like 

\n...

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

, the class\nshould define the do_tag() method.\nThe module defines a single class:\nIn addition to tag methods, the HTMLParser class provides some\nadditional methods and instance variables for use within tag methods.\n---\nnode162.html\nnode139.html\nnode160.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2383, "url": "https://docs.python.org/1.5/lib/node161.html"} {"title": "11.10 Standard Module xmllib", "text": "node163.html\nnode139.html\nnode161.html\nnode1.html\nnode270.html\n---\n# 11.10 Standard Module xmllib\nThis module defines a class XMLParser which serves as the basis\nfor parsing text files formatted in XML (eXtended Markup Language).\nThe XMLParser class must be instantiated without arguments. It\nhas the following interface methods:\nApart from overriding or extending the methods listed above, derived\nclasses may also define methods and variables of the following form to\ndefine processing of specific tags. Tag names in the input stream are\ncase dependent; the tag occurring in method names must be in the\ncorrect case:\n---\nnode163.html\nnode139.html\nnode161.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 702, "url": "https://docs.python.org/1.5/lib/node162.html"} {"title": "11.11 Standard Module formatter", "text": "node164.html\nnode139.html\nnode162.html\nnode1.html\nnode270.html\n---\n# 11.11 Standard Module formatter\nThis module supports two interface definitions, each with mulitple\nimplementations. The formatter interface is used by the\nHTMLParser class of the htmllib 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.\n---\n- The Formatter Interface (node164.html#SECTION00121110000000000000000)\nFormatter Implementations (node165.html#SECTION00121120000000000000000)\nThe Writer Interface (node166.html#SECTION00121130000000000000000)\nWriter Implementations (node167.html#SECTION00121140000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1636, "url": "https://docs.python.org/1.5/lib/node163.html"} {"title": "The Formatter Interface", "text": "node165.html\nnode163.html\nnode163.html\nnode1.html\nnode270.html\n---\n## 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:\n---\nnode165.html\nnode163.html\nnode163.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 504, "url": "https://docs.python.org/1.5/lib/node164.html"} {"title": "Formatter Implementations", "text": "node166.html\nnode163.html\nnode164.html\nnode1.html\nnode270.html\n---\n## Formatter Implementations\nTwo implementations of formatter objects are provided by this module.\nMost applications may use one of these classes without modification or\nsubclassing.\n---\nguido@python.org", "python_version": "1.5", "length": 270, "url": "https://docs.python.org/1.5/lib/node165.html"} {"title": "The Writer Interface", "text": "node167.html\nnode163.html\nnode165.html\nnode1.html\nnode270.html\n---\n## 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 AbstractFormatter\nclass as a formatter, the writer must typically be provided by the\napplication.\n---\nnode167.html\nnode163.html\nnode165.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 518, "url": "https://docs.python.org/1.5/lib/node166.html"} {"title": "Writer Implementations", "text": "node168.html\nnode163.html\nnode166.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nguido@python.org", "python_version": "1.5", "length": 291, "url": "https://docs.python.org/1.5/lib/node167.html"} {"title": "11.12 Standard Module rfc822", "text": "node169.html\nnode139.html\nnode167.html\nnode1.html\nnode270.html\n---\n# 11.12 Standard Module rfc822\nThis module defines a class, Message, which represents a\ncollection of ``email headers'' as defined by the Internet standard\nRFC 822. It is used in various contexts, usually to read such\nheaders from a file.\nNote that there's a separate module to read Unix, MH, and MMDF\nstyle mailbox files: mailbox.\nA Message instance is instantiated with an open file object as\nparameter. The optional seekable parameter indicates if the\nfile object is seekable; the default value is 1 for true.\nInstantiation reads headers from the file up to a blank line and\nstores them in the instance; after instantiation, the file is\npositioned directly after the blank line that terminates the headers.\nInput lines as read from the file may either be terminated by CR-LF or\nby a single linefeed; a terminating CR-LF is replaced by a single\nlinefeed before the line is stored.\nAll header matching is done independent of upper or lower case;\ne.g. m['From'], m['from'] and m['FROM'] all yield\nthe same result.\n---\n- Message Objects (node169.html#SECTION00121210000000000000000)\n---\nnode169.html\nnode139.html\nnode167.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1232, "url": "https://docs.python.org/1.5/lib/node168.html"} {"title": "Message Objects", "text": "node170.html\nnode168.html\nnode168.html\nnode1.html\nnode270.html\n---\n## Message Objects\nA Message instance has the following methods:\nMessage instances also support a read-only mapping interface.\nIn particular: m[name] is the same as m.getheader(name);\nand len(m), m.has_key(name), m.keys(),\nm.values() and m.items() act as expected (and\nconsistently).\nFinally, Message instances have two public instance variables:\n---\nnode170.html\nnode168.html\nnode168.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 497, "url": "https://docs.python.org/1.5/lib/node169.html"} {"title": "Functions", "text": "node18.html\nnode14.html\nnode16.html\nnode1.html\nnode270.html\n---\n### Functions\nFunction objects are created by function definitions. The only\noperation on a function object is to call it:\nfunc(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:\nf.func_code is a function's code object (see below) and\nf.func_globals is the dictionary used as the function's\nglobal name space (this is the same as m.__dict__ where\nm is the module in which the function f was defined).\n---\nguido@python.org", "python_version": "1.5", "length": 732, "url": "https://docs.python.org/1.5/lib/node17.html"} {"title": "11.13 Standard Module mimetools", "text": "node171.html\nnode139.html\nnode169.html\nnode1.html\nnode270.html\n---\n# 11.13 Standard Module mimetools\nThis module defines a subclass of the class rfc822.Message and\na number of utility functions that are useful for the manipulation for\nMIME style multipart or encoded message.\nIt defines the following items:\n---\n- Additional Methods of Message objects (node171.html#SECTION00121310000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 418, "url": "https://docs.python.org/1.5/lib/node170.html"} {"title": "Additional Methods of Message objects", "text": "node172.html\nnode170.html\nnode170.html\nnode1.html\nnode270.html\n---\n## Additional Methods of Message objects\nThe mimetools.Message class defines the following methods in\naddition to the rfc822.Message class:\n---\nguido@python.org", "python_version": "1.5", "length": 227, "url": "https://docs.python.org/1.5/lib/node171.html"} {"title": "11.14 Standard Module binhex", "text": "node173.html\nnode139.html\nnode171.html\nnode1.html\nnode270.html\n---\n# 11.14 Standard Module binhex\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:\n---\n- Notes (node173.html#SECTION00121410000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 488, "url": "https://docs.python.org/1.5/lib/node172.html"} {"title": "Notes", "text": "node174.html\nnode172.html\nnode172.html\nnode1.html\nnode270.html\n---\n## 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).\nAs of this writing, hexbin appears to not work in all cases.\n---\nguido@python.org", "python_version": "1.5", "length": 406, "url": "https://docs.python.org/1.5/lib/node173.html"} {"title": "11.15 Standard Module uu", "text": "node175.html\nnode139.html\nnode173.html\nnode1.html\nnode270.html\n---\n# 11.15 Standard Module uu\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:\n---\nguido@python.org", "python_version": "1.5", "length": 833, "url": "https://docs.python.org/1.5/lib/node174.html"} {"title": "11.16 Built-in Module binascii", "text": "node176.html\nnode139.html\nnode174.html\nnode1.html\nnode270.html\n---\n# 11.16 Built-in Module binascii\nThe binascii module contains a number of methods to convert between\nbinary and various ascii-encoded binary representations. Normally, you\nwill not use these modules directly but use wrapper modules like\nuu or hexbin in stead, this module solely exists because\nbit-manipuation of large amounts of data is slow in python.\nThe binascii module defines the following functions:\n---\nnode176.html\nnode139.html\nnode174.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 557, "url": "https://docs.python.org/1.5/lib/node175.html"} {"title": "11.17 Standard Module xdrlib", "text": "node177.html\nnode139.html\nnode175.html\nnode1.html\nnode270.html\n---\n# 11.17 Standard Module xdrlib\nThe xdrlib module supports the External Data Representation\nStandard as described in RFC 1014, 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.\n---\n- Packer Objects (node177.html#SECTION00121710000000000000000)\nUnpacker Objects (node178.html#SECTION00121720000000000000000)\nExceptions (node179.html#SECTION00121730000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 681, "url": "https://docs.python.org/1.5/lib/node176.html"} {"title": "Packer Objects", "text": "node178.html\nnode176.html\nnode176.html\nnode1.html\nnode270.html\n---\n## Packer Objects\nPacker is the class for packing data into XDR representation.\nThe Packer class is instantiated with no arguments.\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(), pack_int(),\npack_enum(), pack_bool(), pack_uhyper(),\nand pack_hyper().\nThe following methods support packing strings, bytes, and opaque data:\nThe following methods support packing arrays and lists:\n---\nnode178.html\nnode176.html\nnode176.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 721, "url": "https://docs.python.org/1.5/lib/node177.html"} {"title": "Unpacker Objects", "text": "node179.html\nnode176.html\nnode177.html\nnode1.html\nnode270.html\n---\n## Unpacker Objects\nUnpacker is the complementary class which unpacks XDR data\nvalues from a string buffer, and has 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:\n---\nnode179.html\nnode176.html\nnode177.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 624, "url": "https://docs.python.org/1.5/lib/node178.html"} {"title": "Exceptions", "text": "node180.html\nnode176.html\nnode178.html\nnode1.html\nnode270.html\n---\n## Exceptions\nExceptions in this module are coded as class instances:\nHere is an example of how you would catch one of these exceptions:\n```text\nimport xdrlib\np = xdrlib.Packer()\ntry:\np.pack_double(8.01)\nexcept xdrlib.ConversionError, instance:\nprint 'packing the double failed:', instance.msg\n```\n---\nguido@python.org", "python_version": "1.5", "length": 385, "url": "https://docs.python.org/1.5/lib/node179.html"} {"title": "Methods", "text": "node19.html\nnode14.html\nnode17.html\nnode1.html\nnode270.html\n---\n### 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 whose method this\nis, and m.im_func is the function implementing the method.\nCalling m(arg-1, arg-2, ...,\narg-n) is completely equivalent to calling\nm.im_func(m.im_self, arg-1, arg-2,\n..., arg-n).\nSee the Python Reference Manual for more information.\n---\nguido@python.org", "python_version": "1.5", "length": 684, "url": "https://docs.python.org/1.5/lib/node18.html"} {"title": "11.18 Standard Module mailcap", "text": "node181.html\nnode139.html\nnode179.html\nnode1.html\nnode270.html\n---\n# 11.18 Standard Module mailcap\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, %s will be\nreplaced by a filename (usually one belonging to a temporary file) and\nthe xmpeg program can be automatically started to view the file.\nThe mailcap format is documented in RFC 1524, ``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.\nAn example usage:\n```text\n>>> import mailcap\n>>> d=mailcap.getcaps()\n>>> mailcap.findmatch(d, 'video/mpeg', filename='/tmp/tmp1223')\n('xmpeg /tmp/tmp1223', {'view': 'xmpeg %s'})\n```\n---\nnode181.html\nnode139.html\nnode179.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1116, "url": "https://docs.python.org/1.5/lib/node180.html"} {"title": "11.19 Standard Module base64", "text": "node182.html\nnode139.html\nnode180.html\nnode1.html\nnode270.html\n---\n# 11.19 Standard Module base64\nThis module perform base-64 encoding and decoding of arbitrary binary\nstrings into text strings that can be safely emailed or posted. The\nencoding scheme is defined in RFC 1421 and is used for MIME email and\nvarious other Internet-related applications; it is not the same as the\noutput produced by the `uuencode' program. For example, the\nstring 'www.python.org' is encoded as the string\n'd3d3LnB5dGhvbi5vcmc=\\n'.\n---\nguido@python.org", "python_version": "1.5", "length": 532, "url": "https://docs.python.org/1.5/lib/node181.html"} {"title": "11.20 Standard Module quopri", "text": "node183.html\nnode139.html\nnode181.html\nnode1.html\nnode270.html\n---\n# 11.20 Standard Module quopri\nThis module performs quoted-printable transport encoding and decoding,\nas defined in RFC 1521: ``MIME (Multipurpose Internet Mail Extensions)\nPart One''. The quoted-printable encoding is designed for data where\nthere are relatively few nonprintable characters; the base-64 encoding\nscheme available via the base64 module is more compact if there\nare many such characters, as when sending a graphics file.\n---\nguido@python.org", "python_version": "1.5", "length": 523, "url": "https://docs.python.org/1.5/lib/node182.html"} {"title": "11.21 Standard Module SocketServer", "text": "node184.html\nnode139.html\nnode182.html\nnode1.html\nnode270.html\n---\n# 11.21 Standard Module SocketServer\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, and\ncan override any of the following methods. A new instance is created\nfor each request.\n---\nnode184.html\nnode139.html\nnode182.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2273, "url": "https://docs.python.org/1.5/lib/node183.html"} {"title": "11.22 Standard Module mailbox", "text": "node185.html\nnode139.html\nnode183.html\nnode1.html\nnode270.html\n---\n# 11.22 Standard Module mailbox\nThis module defines a number of classes that allow easy and uniform\naccess to mail messages in a (unix) mailbox.\n---\n- Mailbox Objects (node185.html#SECTION00122210000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 300, "url": "https://docs.python.org/1.5/lib/node184.html"} {"title": "Mailbox Objects", "text": "node186.html\nnode184.html\nnode184.html\nnode1.html\nnode270.html\n---\n## Mailbox Objects\nAll implementations of Mailbox objects have one externally visible\nmethod:\n---\nguido@python.org", "python_version": "1.5", "length": 181, "url": "https://docs.python.org/1.5/lib/node185.html"} {"title": "11.23 Standard Module mimify", "text": "node187.html\nnode139.html\nnode185.html\nnode1.html\nnode270.html\n---\n# 11.23 Standard Module mimify\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\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\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.\n---\nnode187.html\nnode139.html\nnode185.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1460, "url": "https://docs.python.org/1.5/lib/node186.html"} {"title": "11.24 Standard Module BaseHTTPServer", "text": "node188.html\nnode139.html\nnode186.html\nnode1.html\nnode270.html\n---\n# 11.24 Standard Module BaseHTTPServer\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 CGIHTTPServer modules.\nThe first class, HTTPServer, is a SocketServer.TCPServer\nsubclass. It creates and listens at the web socket, dispatching the\nrequests to a handler. Code to create and run the server looks like\nthis:\n```text\ndef run(server_class=BaseHTTPServer.HTTPServer,\nhandler_class=BaseHTTPServer.BaseHTTPRequestHandler):\nserver_address = ('', 8000)\nhttpd = server_class(server_address, handler_class)\nhttpd.serve_forever()\n```\nThe HTTPServer class builds on the TCPServer class by\nstoring the server address as instance\nvariables named server_name and server_port. The\nserver is accessible by the handler, typically through the handler's\nserver instance variable.\nThe module's second class, BaseHTTPRequestHandler, is used\nto handle the HTTP requests that arrive at the server. By itself,\nit cannot respond to any actual HTTP requests; it must be subclassed\nto handle each request method (e.g. GET or POST).\nBaseHTTPRequestHandler provides a number of class and instance\nvariables, and methods for use by subclasses.\nThe handler will parse the request and the headers, then call a\nmethod specific to the request type. The method name is constructed\nfrom the request. For example, for the request SPAM, the\ndo_SPAM method will be called with no arguments. All of\nthe relevant information is stored into instance variables of the\nhandler.\nBaseHTTPRequestHandler has the following instance variables:\nBaseHTTPRequestHandler has the following class variables:\nA BaseHTTPRequestHandler instance has the following methods:\n---\nnode188.html\nnode139.html\nnode186.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1926, "url": "https://docs.python.org/1.5/lib/node187.html"} {"title": "12 Restricted Execution", "text": "node189.html\nlib.html\nnode187.html\nnode1.html\nnode270.html\n---\n# 12 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 OS\ngives 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\nopen() function so that it raises an exception whenever the\nmode parameter is 'w'. It might also perform a\nchroot()-like operation on the filename parameter, such\nthat root is always relative to some safe ``sandbox'' area of the\nfilesystem. In this case, the untrusted code would still see an\nbuilt-in open() function in its environment, with the same\ncalling interface. The semantics would be identical too, with\nIOErrors being raised when the supervisor determined that an\nunallowable 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, the code is\ndeemed to be unrestricted, else it is deemed to be restricted.\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 the\nclass and instance object attribute __dict__ are unavailable.\nTwo modules provide the framework for setting up restricted execution\nenvironments:\n---\n- 12.1 Standard Module rexec (node189.html#SECTION0013100000000000000000)\n- An example (node190.html#SECTION0013110000000000000000)\n12.2 Standard Module Bastion (node191.html#SECTION0013200000000000000000)\n---\nnode189.html\nlib.html\nnode187.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3713, "url": "https://docs.python.org/1.5/lib/node188.html"} {"title": "12.1 Standard Module rexec", "text": "node190.html\nnode188.html\nnode188.html\nnode1.html\nnode270.html\n---\n# 12.1 Standard Module rexec\nThis module contains the RExec class, which supports\nr_exec(), r_eval(), r_execfile(), and\nr_import() methods, which are restricted versions of the standard\nPython functions exec(), eval(), execfile(), and\nthe import statement.\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 streans sys.stdin,\nsys.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:\n---\n- An example (node190.html#SECTION0013110000000000000000)\n---\nnode190.html\nnode188.html\nnode188.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1784, "url": "https://docs.python.org/1.5/lib/node189.html"} {"title": "Code Objects", "text": "node20.html\nnode14.html\nnode18.html\nnode1.html\nnode270.html\n---\n### 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 for more information.\n---\nguido@python.org", "python_version": "1.5", "length": 672, "url": "https://docs.python.org/1.5/lib/node19.html"} {"title": "An example", "text": "node191.html\nnode189.html\nnode189.html\nnode1.html\nnode270.html\n---\n## 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:\n```text\nclass TmpWriterRExec(rexec.RExec):\ndef r_open(self, file, mode='r', buf=-1):\nif mode in ('r', 'rb'):\npass\nelif mode in ('w', 'wb', 'a', 'ab'):\n# check filename : must begin with /tmp/\nif file[:5]!='/tmp/':\nraise IOError, \"can't write outside /tmp\"\nelif (string.find(file, '/../') >= 0 or\nfile[:3] == '../' or file[-3:] == '/..'):\nraise IOError, \"'..' in filename forbidden\"\nelse: raise IOError, \"Illegal open() mode\"\nreturn open(file, mode, buf)\n```\nNotice that the above code will occasionally forbid a perfectly valid\nfilename; for example, code in the restricted environment won't be\nable to open a file called `/tmp/foo/../bar'. To fix this, the\nr_open method would have to simplify the filename to\n`/tmp/bar', which would require splitting apart the filename and\nperforming various operations on it. In cases where security is at\nstake, it may be preferable to write simple code which is sometimes\noverly restrictive, instead of more general code that is also more\ncomplex and may harbor a subtle security hole.\n---\nguido@python.org", "python_version": "1.5", "length": 1315, "url": "https://docs.python.org/1.5/lib/node190.html"} {"title": "12.2 Standard Module Bastion", "text": "node192.html\nnode188.html\nnode190.html\nnode1.html\nnode270.html\n---\n# 12.2 Standard Module Bastion\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, in order to allow restricted-mode programs access\nto certain safe attributes of an object, while denying access to\nother, unsafe attributes.\n---\nguido@python.org", "python_version": "1.5", "length": 543, "url": "https://docs.python.org/1.5/lib/node191.html"} {"title": "13 Multimedia Services", "text": "node193.html\nlib.html\nnode191.html\nnode1.html\nnode270.html\n---\n# 13 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:\n---\n- 13.1 Built-in Module audioop (node193.html#SECTION0014100000000000000000)\n13.2 Built-in Module imageop (node194.html#SECTION0014200000000000000000)\n13.3 Standard Module aifc (node195.html#SECTION0014300000000000000000)\n13.4 Built-in Module jpeg (node196.html#SECTION0014400000000000000000)\n13.5 Built-in Module rgbimg (node197.html#SECTION0014500000000000000000)\n13.6 Standard Module imghdr (node198.html#SECTION0014600000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 761, "url": "https://docs.python.org/1.5/lib/node192.html"} {"title": "13.1 Built-in Module audioop", "text": "node194.html\nnode192.html\nnode192.html\nnode1.html\nnode270.html\n---\n# 13.1 Built-in Module audioop\nThe audioop module contains some useful operations on sound fragments.\nIt operates on sound fragments consisting of signed integer samples\n8, 16 or 32 bits wide, stored in Python strings. This is the same\nformat as used by the al and sunaudiodev modules. All\nscalar items are integers, unless specified otherwise.\nA few of the more complicated operations only take 16-bit samples,\notherwise the sample size (in bytes) is always a parameter of the operation.\nThe module defines the following variables and functions:\nNote that operations such as mul or max make no\ndistinction between mono and stereo fragments, i.e. all samples are\ntreated equal. If this is a problem the stereo fragment should be split\ninto two mono fragments first and recombined later. Here is an example\nof how to do that:\n```text\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 returned by\nthe coder). If you want to use struct to store the state in\nbinary you can code the first element (the predicted value) in 16 bits\nand 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:\n```text\ndef echocancel(outputdata, inputdata):\npos = audioop.findmax(outputdata, 800) # one tenth second\nout_test = outputdata[pos*2:]\nin_test = inputdata[pos*2:]\nipos, factor = audioop.findfit(in_test, out_test)\n# Optional (for better cancellation):\n# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],\n# out_test)\nprefill = '\\0'*(pos+ipos)*2\npostfill = '\\0'*(len(inputdata)-len(prefill)-len(outputdata))\noutputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill\nreturn audioop.add(inputdata, outputdata, 2)\n```\n---\nnode194.html\nnode192.html\nnode192.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2915, "url": "https://docs.python.org/1.5/lib/node193.html"} {"title": "13.2 Built-in Module imageop", "text": "node195.html\nnode192.html\nnode193.html\nnode1.html\nnode270.html\n---\n# 13.2 Built-in Module imageop\nThe imageop module contains some useful operations on images.\nIt operates on images consisting of 8 or 32 bit pixels\nstored in Python strings. This is the same format as used\nby gl.lrectwrite and the imgfile module.\nThe module defines the following variables and functions:\n---\nnode195.html\nnode192.html\nnode193.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 455, "url": "https://docs.python.org/1.5/lib/node194.html"} {"title": "13.3 Standard Module aifc", "text": "node196.html\nnode192.html\nnode194.html\nnode1.html\nnode270.html\n---\n# 13.3 Standard Module aifc\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.\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 aifc.open() when a file is opened for\nreading have the following methods:\nObjects returned by aifc.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 except\nfor the number of frames must be filled in.\n---\nnode196.html\nnode192.html\nnode194.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1673, "url": "https://docs.python.org/1.5/lib/node195.html"} {"title": "13.4 Built-in Module jpeg", "text": "node197.html\nnode192.html\nnode195.html\nnode1.html\nnode270.html\n---\n# 13.4 Built-in Module jpeg\nThe module jpeg provides access to the jpeg compressor and\ndecompressor written by the Independent JPEG Group. JPEG is a (draft?)\\\nstandard for compressing pictures. For details on jpeg or the\nIndependent JPEG Group software refer to the JPEG standard or the\ndocumentation provided with the software.\nThe jpeg module defines these functions:\nCompress and uncompress raise the error jpeg.error in case of errors.\n---\nguido@python.org", "python_version": "1.5", "length": 527, "url": "https://docs.python.org/1.5/lib/node196.html"} {"title": "13.5 Built-in Module rgbimg", "text": "node198.html\nnode192.html\nnode196.html\nnode1.html\nnode270.html\n---\n# 13.5 Built-in Module rgbimg\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\nis enough in some cases. Currently, colormap files are not supported.\nThe module defines the following variables and functions:\n---\nguido@python.org", "python_version": "1.5", "length": 443, "url": "https://docs.python.org/1.5/lib/node197.html"} {"title": "13.6 Standard Module imghdr", "text": "node199.html\nnode192.html\nnode197.html\nnode1.html\nnode270.html\n---\n# 13.6 Standard Module imghdr\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:\n```text\n>>> import imghdr\n>>> imghdr.what('/tmp/bass.gif')\n'gif'\n```\n---\nguido@python.org", "python_version": "1.5", "length": 509, "url": "https://docs.python.org/1.5/lib/node198.html"} {"title": "14 Cryptographic Services", "text": "node200.html\nlib.html\nnode198.html\nnode1.html\nnode270.html\n---\n# 14 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:\nHardcore cypherpunks will probably find the cryptographic modules\nwritten by Andrew Kuchling of further interest; the package adds\nbuilt-in modules for DES and IDEA encryption, provides a Python module\nfor reading and decrypting PGP files, and then some. These modules\nare not distributed with Python but available separately. See the URL\nhttp://www.magnet.com/ãmk/python/pct.html or send email to\namk@magnet.com for more information.\n---\n- 14.1 Built-in Module md5 (node200.html#SECTION0015100000000000000000)\n14.2 Built-in Module mpz (node201.html#SECTION0015200000000000000000)\n14.3 Built-in Module rotor (node202.html#SECTION0015300000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 936, "url": "https://docs.python.org/1.5/lib/node199.html"} {"title": "1 Introduction", "text": "node3.html\nlib.html\nnode1.html\nnode1.html\nnode270.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, like socket I/O; others provide interfaces 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\nrand) and read a section or two.\nLet the show begin!\n---\nnode3.html\nlib.html\nnode1.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2643, "url": "https://docs.python.org/1.5/lib/node2.html"} {"title": "Type Objects", "text": "node21.html\nnode14.html\nnode19.html\nnode1.html\nnode270.html\n---\n### 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: .\n---\nguido@python.org", "python_version": "1.5", "length": 370, "url": "https://docs.python.org/1.5/lib/node20.html"} {"title": "14.1 Built-in Module md5", "text": "node201.html\nnode199.html\nnode199.html\nnode1.html\nnode270.html\n---\n# 14.1 Built-in Module md5\nThis module implements the interface to RSA's MD5 message digest\nalgorithm (see also Internet RFC 1321). Its use is quite\nstraightforward: use the md5.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>>> 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>>> 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:\n---\nguido@python.org", "python_version": "1.5", "length": 1047, "url": "https://docs.python.org/1.5/lib/node200.html"} {"title": "14.2 Built-in Module mpz", "text": "node202.html\nnode199.html\nnode200.html\nnode1.html\nnode270.html\n---\n# 14.2 Built-in Module mpz\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.\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, pow.\nPlease note: the bitwise-xor operation has been implemented as\na bunch of ands, inverts and ors, because the library\nlacks an mpz_xor function, and I didn't need one.\nYou create an mpz-number by calling the function called mpz (see\nbelow for an exact description). An mpz-number is printed like this:\nmpz(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:\n---\nnode202.html\nnode199.html\nnode200.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1327, "url": "https://docs.python.org/1.5/lib/node201.html"} {"title": "14.3 Built-in Module rotor", "text": "node203.html\nnode199.html\nnode201.html\nnode1.html\nnode270.html\n---\n# 14.3 Built-in Module rotor\nThis module implements a rotor-based encryption algorithm, contributed by\nLance Ellinghouse. The design is derived from 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>>> 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 device;\nit implements the rotor encryption scheme differently from the original. The\nmost important difference is that in the original Enigma, there were only 5\nor 6 different rotors in existence, and they were applied twice to each\ncharacter; the cipher key was the order in which they were placed in the\nmachine. The Python rotor module uses the supplied key to initialize a\nrandom number generator; the rotor permutations and their initial positions\nare then randomly generated. The original device only enciphered the\nletters of the alphabet, while this module can handle any 8-bit binary data;\nit also produces 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.\n---\nnode203.html\nnode199.html\nnode201.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3016, "url": "https://docs.python.org/1.5/lib/node202.html"} {"title": "15 Macintosh Specific Services", "text": "node204.html\nlib.html\nnode202.html\nnode1.html\nnode270.html\n---\n# 15 Macintosh Specific Services\nThe modules in this chapter 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__\nstring describing their arguments and return values, and for\nadditional description you are referred to Inside Mac or similar\nworks.\n---\n- 15.1 Built-in Module mac (node204.html#SECTION0016100000000000000000)\n15.2 Standard Module macpath (node205.html#SECTION0016200000000000000000)\n15.3 Built-in Module ctb (node206.html#SECTION0016300000000000000000)\n- connection object (node207.html#SECTION0016310000000000000000)\n15.4 Built-in Module macconsole (node208.html#SECTION0016400000000000000000)\n- macconsole options object (node209.html#SECTION0016410000000000000000)\nconsole window object (node210.html#SECTION0016420000000000000000)\n15.5 Built-in Module macdnr (node211.html#SECTION0016500000000000000000)\n- dnr result object (node212.html#SECTION0016510000000000000000)\n15.6 Built-in Module macfs (node213.html#SECTION0016600000000000000000)\n- FSSpec objects (node214.html#SECTION0016610000000000000000)\nalias objects (node215.html#SECTION0016620000000000000000)\nFInfo objects (node216.html#SECTION0016630000000000000000)\n15.7 Standard Module ic (node217.html#SECTION0016700000000000000000)\n- IC objects (node218.html#SECTION0016710000000000000000)\n15.8 Built-in Module MacOS (node219.html#SECTION0016800000000000000000)\n15.9 Standard Module macostools (node220.html#SECTION0016900000000000000000)\n15.10 Standard Module findertools (node221.html#SECTION00161000000000000000000)\n15.11 Built-in Module mactcp (node222.html#SECTION00161100000000000000000)\n- TCP Stream Objects (node223.html#SECTION00161110000000000000000)\nTCP Status Objects (node224.html#SECTION00161120000000000000000)\nUDP Stream Objects (node225.html#SECTION00161130000000000000000)\n15.12 Built-in Module macspeech (node226.html#SECTION00161200000000000000000)\n- voice objects (node227.html#SECTION00161210000000000000000)\nspeech channel objects (node228.html#SECTION00161220000000000000000)\n15.13 Standard Module EasyDialogs (node229.html#SECTION00161300000000000000000)\n15.14 Standard Module FrameWork (node230.html#SECTION00161400000000000000000)\n- Application objects (node231.html#SECTION00161410000000000000000)\nWindow Objects (node232.html#SECTION00161420000000000000000)\nControlsWindow Object (node233.html#SECTION00161430000000000000000)\nScrolledWindow Object (node234.html#SECTION00161440000000000000000)\nDialogWindow Objects (node235.html#SECTION00161450000000000000000)\n15.15 Standard Module MiniAEFrame (node236.html#SECTION00161500000000000000000)\n- AEServer Objects (node237.html#SECTION00161510000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 3706, "url": "https://docs.python.org/1.5/lib/node203.html"} {"title": "15.1 Built-in Module mac", "text": "node205.html\nnode203.html\nnode203.html\nnode1.html\nnode270.html\n---\n# 15.1 Built-in Module mac\nThis module provides a subset of the operating system dependent\nfunctionality provided by the optional built-in module posix.\nIt is best accessed through the more portable standard module\nos.\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 returned by\nstat() are floating-point values, like all time values in\nMacPython.\nOne additional function is available: xstat(). This function\nreturns the same information as stat(), but with three extra\nvalues appended: the size of the resource fork of the file and its\n4-char creator and type.\n---\nguido@python.org", "python_version": "1.5", "length": 819, "url": "https://docs.python.org/1.5/lib/node204.html"} {"title": "15.2 Standard Module macpath", "text": "node206.html\nnode203.html\nnode204.html\nnode1.html\nnode270.html\n---\n# 15.2 Standard Module macpath\nThis module provides a subset of the pathname manipulation functions\navailable from the optional standard module posixpath. It is\nbest accessed through the more portable standard module os, as\nos.path.\nThe following functions are available in this module:\nnormcase,\nnormpath,\nisabs,\njoin,\nsplit,\nisdir,\nisfile,\nwalk,\nexists.\nFor other functions available in posixpath dummy counterparts\nare available.\n---\nguido@python.org", "python_version": "1.5", "length": 520, "url": "https://docs.python.org/1.5/lib/node205.html"} {"title": "15.3 Built-in Module ctb", "text": "node207.html\nnode203.html\nnode205.html\nnode1.html\nnode270.html\n---\n# 15.3 Built-in Module ctb\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.\n---\n- connection object (node207.html#SECTION0016310000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 373, "url": "https://docs.python.org/1.5/lib/node206.html"} {"title": "connection object", "text": "node208.html\nnode206.html\nnode206.html\nnode1.html\nnode270.html\n---\n## connection object\nFor all connection methods that take a timeout argument, a value\nof -1 is indefinite, meaning that the command runs to completion.\n---\nnode208.html\nnode206.html\nnode206.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 302, "url": "https://docs.python.org/1.5/lib/node207.html"} {"title": "15.4 Built-in Module macconsole", "text": "node209.html\nnode203.html\nnode207.html\nnode1.html\nnode270.html\n---\n# 15.4 Built-in Module macconsole\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.\n---\n- macconsole options object (node209.html#SECTION0016410000000000000000)\nconsole window object (node210.html#SECTION0016420000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 468, "url": "https://docs.python.org/1.5/lib/node208.html"} {"title": "macconsole options object", "text": "node210.html\nnode208.html\nnode208.html\nnode1.html\nnode270.html\n---\n## macconsole options object\nThese options are examined when a window is created:\n---\nguido@python.org", "python_version": "1.5", "length": 169, "url": "https://docs.python.org/1.5/lib/node209.html"} {"title": "The Null Object", "text": "node22.html\nnode14.html\nnode20.html\nnode1.html\nnode270.html\n---\n### 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.\n---\nguido@python.org", "python_version": "1.5", "length": 301, "url": "https://docs.python.org/1.5/lib/node21.html"} {"title": "console window object", "text": "node211.html\nnode208.html\nnode209.html\nnode1.html\nnode270.html\n---\n## console window object\n---\nguido@python.org", "python_version": "1.5", "length": 112, "url": "https://docs.python.org/1.5/lib/node210.html"} {"title": "15.5 Built-in Module macdnr", "text": "node212.html\nnode203.html\nnode210.html\nnode1.html\nnode270.html\n---\n# 15.5 Built-in Module macdnr\nThis module provides an interface to the Macintosh Domain Name\nResolver. It is usually used in conjunction with the mactcp\nmodule, to map hostnames to IP-addresses. It may not be available in\nall Mac Python versions.\nThe macdnr module defines the following functions:\n---\n- dnr result object (node212.html#SECTION0016510000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 454, "url": "https://docs.python.org/1.5/lib/node211.html"} {"title": "dnr result object", "text": "node213.html\nnode211.html\nnode211.html\nnode1.html\nnode270.html\n---\n## dnr result object\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 available, the\nothers depend on the type of query (address, hinfo or mx).\nThe simplest way to use the module to convert names to dotted-decimal\nstrings, without worrying about idle time, etc:\n```text\n>>> def gethostname(name):\n... import macdnr\n... dnrr = macdnr.StrToAddr(name)\n... return macdnr.AddrToStr(dnrr.ip0)\n```\n---\nguido@python.org", "python_version": "1.5", "length": 865, "url": "https://docs.python.org/1.5/lib/node212.html"} {"title": "15.6 Built-in Module macfs", "text": "node214.html\nnode203.html\nnode212.html\nnode1.html\nnode270.html\n---\n# 15.6 Built-in Module macfs\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,\nparID, name) as described in Inside Mac VI. A description of aliases\nand the standard file package can also be found there.\n---\n- FSSpec objects (node214.html#SECTION0016610000000000000000)\nalias objects (node215.html#SECTION0016620000000000000000)\nFInfo objects (node216.html#SECTION0016630000000000000000)\n---\nnode214.html\nnode203.html\nnode212.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 798, "url": "https://docs.python.org/1.5/lib/node213.html"} {"title": "FSSpec objects", "text": "node215.html\nnode213.html\nnode213.html\nnode1.html\nnode270.html\n---\n## FSSpec objects\n---\nguido@python.org", "python_version": "1.5", "length": 105, "url": "https://docs.python.org/1.5/lib/node214.html"} {"title": "alias objects", "text": "node216.html\nnode213.html\nnode214.html\nnode1.html\nnode270.html\n---\n## alias objects\nNote that it is currently not possible to directly manipulate a resource\nas an alias object. Hence, after calling Update or after\nResolve indicates that the alias has changed the Python program\nis responsible for getting the data from the alias object and\nmodifying the resource.\n---\nguido@python.org", "python_version": "1.5", "length": 384, "url": "https://docs.python.org/1.5/lib/node215.html"} {"title": "FInfo objects", "text": "node217.html\nnode213.html\nnode215.html\nnode1.html\nnode270.html\n---\n## FInfo objects\nSee Inside Mac for a complete description of what the various fields\nmean.\n---\nguido@python.org", "python_version": "1.5", "length": 179, "url": "https://docs.python.org/1.5/lib/node216.html"} {"title": "15.7 Standard Module ic", "text": "node218.html\nnode203.html\nnode216.html\nnode1.html\nnode270.html\n---\n# 15.7 Standard Module ic\nThis module provides access to macintosh Internet Config 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 icglue which provides the\nbasic ic 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 symbolic\nnames for all error codes IC can produce, see the source for details.\nThe ic module defines the following functions:\n---\n- IC objects (node218.html#SECTION0016710000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1054, "url": "https://docs.python.org/1.5/lib/node217.html"} {"title": "IC objects", "text": "node219.html\nnode217.html\nnode217.html\nnode1.html\nnode270.html\n---\n## IC objects\nIC objects have a mapping interface, hence to obtain the mail address\nyou simply get ic['MailAddress']. Assignment also works, and\nchanges the option in the configuration file.\nThe module knows about various datatypes, and converts the internal IC\nrepresentation to a ``logical'' python datastructure. 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 following methods:\n---\nnode219.html\nnode217.html\nnode217.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 898, "url": "https://docs.python.org/1.5/lib/node218.html"} {"title": "15.8 Built-in Module MacOS", "text": "node220.html\nnode203.html\nnode218.html\nnode1.html\nnode270.html\n---\n# 15.8 Built-in Module MacOS\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\nartefact.\n---\nnode220.html\nnode203.html\nnode218.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 418, "url": "https://docs.python.org/1.5/lib/node219.html"} {"title": "File Objects", "text": "node23.html\nnode14.html\nnode21.html\nnode1.html\nnode270.html\n---\n### File Objects\nFile objects are implemented using C's stdio package and can be\ncreated with the built-in function open() described under\nBuilt-in Functions below. They are also returned by some other\nbuilt-in functions and methods, e.g. posix.popen() and\nposix.fdopen() and the makefile() method of socket\nobjects.\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:\n---\nnode23.html\nnode14.html\nnode21.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 776, "url": "https://docs.python.org/1.5/lib/node22.html"} {"title": "15.9 Standard Module macostools", "text": "node221.html\nnode203.html\nnode219.html\nnode1.html\nnode270.html\n---\n# 15.9 Standard Module macostools\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.\n---\nguido@python.org", "python_version": "1.5", "length": 454, "url": "https://docs.python.org/1.5/lib/node220.html"} {"title": "15.10 Standard Module findertools", "text": "node222.html\nnode203.html\nnode220.html\nnode1.html\nnode270.html\n---\n# 15.10 Standard Module findertools\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:\n---\nguido@python.org", "python_version": "1.5", "length": 463, "url": "https://docs.python.org/1.5/lib/node221.html"} {"title": "15.11 Built-in Module mactcp", "text": "node223.html\nnode203.html\nnode221.html\nnode1.html\nnode270.html\n---\n# 15.11 Built-in Module mactcp\nThis module provides an interface to the Macintosh TCP/IP driver\nMacTCP. There is an accompanying module macdnr which provides an\ninterface to the name-server (allowing you to translate hostnames to\nip-addresses), a module MACTCPconst which has symbolic names for\nconstants constants used by MacTCP. Since the builtin module\nsocket is also available on the mac it is usually easier to use\nsockets in stead of the mac-specific MacTCP API.\nA complete description of the MacTCP interface can be found in the\nApple MacTCP API documentation.\n---\n- TCP Stream Objects (node223.html#SECTION00161110000000000000000)\nTCP Status Objects (node224.html#SECTION00161120000000000000000)\nUDP Stream Objects (node225.html#SECTION00161130000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 856, "url": "https://docs.python.org/1.5/lib/node222.html"} {"title": "TCP Stream Objects", "text": "node224.html\nnode222.html\nnode222.html\nnode1.html\nnode270.html\n---\n## TCP Stream Objects\n---\nnode224.html\nnode222.html\nnode222.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 172, "url": "https://docs.python.org/1.5/lib/node223.html"} {"title": "TCP Status Objects", "text": "node225.html\nnode222.html\nnode223.html\nnode1.html\nnode270.html\n---\n## 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:\n---\nguido@python.org", "python_version": "1.5", "length": 319, "url": "https://docs.python.org/1.5/lib/node224.html"} {"title": "UDP Stream Objects", "text": "node226.html\nnode222.html\nnode224.html\nnode1.html\nnode270.html\n---\n## UDP Stream Objects\nNote that, unlike the name suggests, there is nothing stream-like\nabout UDP.\n---\nguido@python.org", "python_version": "1.5", "length": 186, "url": "https://docs.python.org/1.5/lib/node225.html"} {"title": "15.12 Built-in Module macspeech", "text": "node227.html\nnode203.html\nnode225.html\nnode1.html\nnode270.html\n---\n# 15.12 Built-in Module macspeech\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.\n---\n- voice objects (node227.html#SECTION00161210000000000000000)\nspeech channel objects (node228.html#SECTION00161220000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 637, "url": "https://docs.python.org/1.5/lib/node226.html"} {"title": "voice objects", "text": "node228.html\nnode226.html\nnode226.html\nnode1.html\nnode270.html\n---\n## voice objects\nVoice objects contain the description of a voice. It is currently not\nyet possible to access the parameters of a voice.\n---\nguido@python.org", "python_version": "1.5", "length": 224, "url": "https://docs.python.org/1.5/lib/node227.html"} {"title": "speech channel objects", "text": "node229.html\nnode226.html\nnode227.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nguido@python.org", "python_version": "1.5", "length": 406, "url": "https://docs.python.org/1.5/lib/node228.html"} {"title": "15.13 Standard Module EasyDialogs", "text": "node230.html\nnode203.html\nnode228.html\nnode1.html\nnode270.html\n---\n# 15.13 Standard Module EasyDialogs\nThe EasyDialogs module contains some simple dialogs for\nthe Macintosh, modelled after the stdwin dialogs with similar\nnames. All routines have an optional parameter id with which you\ncan override the DLOG resource used for the dialog, as long as the\nitem numbers correspond. See the source for details.\nThe EasyDialogs module defines the following functions:\nNote that EasyDialogs does not currently use the notification\nmanager. This means that displaying dialogs while the program is in\nthe background will lead to unexpected results and possibly\ncrashes. Also, all dialogs are modeless and hence expect to be at the\ntop of the stacking order. This is true when the dialogs are created,\nbut windows that pop-up later (like a console window) may also result\nin crashes.\n---\nnode230.html\nnode203.html\nnode228.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 957, "url": "https://docs.python.org/1.5/lib/node229.html"} {"title": "Internal Objects", "text": "node24.html\nnode14.html\nnode22.html\nnode1.html\nnode270.html\n---\n### Internal Objects\nSee the Python Reference Manual for this information. It\ndescribes code objects, stack frame objects, traceback objects, and\nslice objects.\n---\nguido@python.org", "python_version": "1.5", "length": 245, "url": "https://docs.python.org/1.5/lib/node23.html"} {"title": "15.14 Standard Module FrameWork", "text": "node231.html\nnode203.html\nnode229.html\nnode1.html\nnode270.html\n---\n# 15.14 Standard Module FrameWork\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:\n---\n- Application objects (node231.html#SECTION00161410000000000000000)\nWindow Objects (node232.html#SECTION00161420000000000000000)\nControlsWindow Object (node233.html#SECTION00161430000000000000000)\nScrolledWindow Object (node234.html#SECTION00161440000000000000000)\nDialogWindow Objects (node235.html#SECTION00161450000000000000000)\n---\nnode231.html\nnode203.html\nnode229.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1269, "url": "https://docs.python.org/1.5/lib/node230.html"} {"title": "Application objects", "text": "node232.html\nnode230.html\nnode230.html\nnode1.html\nnode270.html\n---\n## Application objects\nApplication objects have the following methods, among others:\n---\nnode232.html\nnode230.html\nnode230.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 235, "url": "https://docs.python.org/1.5/lib/node231.html"} {"title": "Window Objects", "text": "node233.html\nnode230.html\nnode231.html\nnode1.html\nnode270.html\n---\n## Window Objects\nWindow objects have the following methods, among others:\n---\nguido@python.org", "python_version": "1.5", "length": 162, "url": "https://docs.python.org/1.5/lib/node232.html"} {"title": "ControlsWindow Object", "text": "node234.html\nnode230.html\nnode232.html\nnode1.html\nnode270.html\n---\n## ControlsWindow Object\nControlsWindow objects have the following methods besides those of\nWindow objects:\n---\nguido@python.org", "python_version": "1.5", "length": 195, "url": "https://docs.python.org/1.5/lib/node233.html"} {"title": "ScrolledWindow Object", "text": "node235.html\nnode230.html\nnode233.html\nnode1.html\nnode270.html\n---\n## ScrolledWindow Object\nScrolledWindow objects are ControlsWindow objects with the following\nextra methods:\n---\nguido@python.org", "python_version": "1.5", "length": 196, "url": "https://docs.python.org/1.5/lib/node234.html"} {"title": "DialogWindow Objects", "text": "node236.html\nnode230.html\nnode234.html\nnode1.html\nnode270.html\n---\n## DialogWindow Objects\nDialogWindow objects have the following methods besides those of\nWindow objects:\n---\nguido@python.org", "python_version": "1.5", "length": 192, "url": "https://docs.python.org/1.5/lib/node235.html"} {"title": "15.15 Standard Module MiniAEFrame", "text": "node237.html\nnode203.html\nnode235.html\nnode1.html\nnode270.html\n---\n# 15.15 Standard Module MiniAEFrame\nThe module MiniAEFrame provides a framework for an application\nthat can function as an OSA server, i.e. receive and process\nAppleEvents. It can be used in conjunction with FrameWork or\nstandalone.\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:\n---\n- AEServer Objects (node237.html#SECTION00161510000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 606, "url": "https://docs.python.org/1.5/lib/node236.html"} {"title": "AEServer Objects", "text": "node238.html\nnode236.html\nnode236.html\nnode1.html\nnode270.html\n---\n## AEServer Objects\nNote that there are some serious problems with the current\ndesign. AppleEvents which have non-identifier 4-char designators for\narguments are not implementable, and it is not possible to return an\nerror to the originator. This will be addressed in a future release.\n---\nguido@python.org", "python_version": "1.5", "length": 373, "url": "https://docs.python.org/1.5/lib/node237.html"} {"title": "16 SGI IRIX Specific Services", "text": "node239.html\nlib.html\nnode237.html\nnode1.html\nnode270.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).\n---\n- 16.1 Built-in Module al (node239.html#SECTION0017100000000000000000)\n- Configuration Objects (node240.html#SECTION0017110000000000000000)\nPort Objects (node241.html#SECTION0017120000000000000000)\n16.2 Standard Module AL (node242.html#SECTION0017200000000000000000)\n16.3 Built-in Module cd (node243.html#SECTION0017300000000000000000)\n16.4 Built-in Module fl (node244.html#SECTION0017400000000000000000)\n- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)\nForm Objects (node246.html#SECTION0017420000000000000000)\nFORMS Objects (node247.html#SECTION0017430000000000000000)\n16.5 Standard Module FL (node248.html#SECTION0017500000000000000000)\n16.6 Standard Module flp (node249.html#SECTION0017600000000000000000)\n16.7 Built-in Module fm (node250.html#SECTION0017700000000000000000)\n16.8 Built-in Module gl (node251.html#SECTION0017800000000000000000)\n16.9 Standard Modules GL and DEVICE (node252.html#SECTION0017900000000000000000)\n16.10 Built-in Module imgfile (node253.html#SECTION00171000000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1289, "url": "https://docs.python.org/1.5/lib/node238.html"} {"title": "16.1 Built-in Module al", "text": "node240.html\nnode238.html\nnode238.html\nnode1.html\nnode270.html\n---\n# 16.1 Built-in Module al\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 defined\nin the standard module AL, 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:\n---\n- Configuration Objects (node240.html#SECTION0017110000000000000000)\nPort Objects (node241.html#SECTION0017120000000000000000)\n---\nnode240.html\nnode238.html\nnode238.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1370, "url": "https://docs.python.org/1.5/lib/node239.html"} {"title": "Special Attributes", "text": "node25.html\nnode4.html\nnode23.html\nnode1.html\nnode270.html\n---\n## Special Attributes\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant:\n- x.__dict__ is a dictionary of some sort used to store an\nobject's (writable) attributes;x.__methods__ lists the methods of many built-in object types,\ne.g., [].__methods__ yields\n['append', 'count', 'index', 'insert', 'remove', 'reverse', 'sort'];x.__members__ lists data attributes;x.__class__ is the class to which a class instance belongs;x.__bases__ is the tuple of base classes of a class object.\n---\nguido@python.org", "python_version": "1.5", "length": 618, "url": "https://docs.python.org/1.5/lib/node24.html"} {"title": "Configuration Objects", "text": "node241.html\nnode239.html\nnode239.html\nnode1.html\nnode270.html\n---\n## Configuration Objects\nConfiguration objects (returned by al.newconfig() have the\nfollowing methods:\n---\nguido@python.org", "python_version": "1.5", "length": 190, "url": "https://docs.python.org/1.5/lib/node240.html"} {"title": "Port Objects", "text": "node242.html\nnode239.html\nnode240.html\nnode1.html\nnode270.html\n---\n## Port Objects\nPort objects (returned by al.openport() have the following\nmethods:\n---\nguido@python.org", "python_version": "1.5", "length": 171, "url": "https://docs.python.org/1.5/lib/node241.html"} {"title": "16.2 Standard Module AL", "text": "node243.html\nnode238.html\nnode241.html\nnode1.html\nnode270.html\n---\n# 16.2 Standard Module AL\nThis module defines symbolic constants needed to use the built-in\nmodule al (see above); they are equivalent to those defined in\nthe 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:\n```text\nimport al\nfrom AL import *\n```\n---\nguido@python.org", "python_version": "1.5", "length": 437, "url": "https://docs.python.org/1.5/lib/node242.html"} {"title": "16.3 Built-in Module cd", "text": "node244.html\nnode238.html\nnode242.html\nnode1.html\nnode270.html\n---\n# 16.3 Built-in Module cd\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 cd.open() and creates a parser to parse the data\nfrom the CD with cd.createparser(). The object returned by\ncd.open() 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 getstatus:\nPlayer objects (returned by cd.open()) have the following\nmethods:\nParser objects (returned by cd.createparser()) have the\nfollowing methods:\n---\nnode244.html\nnode238.html\nnode242.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1726, "url": "https://docs.python.org/1.5/lib/node243.html"} {"title": "16.4 Built-in Module fl", "text": "node245.html\nnode238.html\nnode243.html\nnode1.html\nnode270.html\n---\n# 16.4 Built-in Module fl\nThis module provides an interface to the FORMS Library by Mark\nOvermars. The source for the library can be retrieved by anonymous\nftp from host `ftp.cs.ruu.nl', directory `SGI/FORMS'. It\nwas last tested with 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 described 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 equivalent of\nfl_bgn_form is called fl.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 function\nforeground() and to the FORMS routine fl_init().\n---\n- Functions Defined in Module fl (node245.html#SECTION0017410000000000000000)\nForm Objects (node246.html#SECTION0017420000000000000000)\nFORMS Objects (node247.html#SECTION0017430000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1860, "url": "https://docs.python.org/1.5/lib/node244.html"} {"title": "Functions Defined in Module fl", "text": "node246.html\nnode244.html\nnode244.html\nnode1.html\nnode270.html\n---\n## Functions Defined in Module fl\nModule fl defines the following functions. For more information\nabout what they do, see the description of the equivalent C function\nin the FORMS documentation:\n---\nnode246.html\nnode244.html\nnode244.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 345, "url": "https://docs.python.org/1.5/lib/node245.html"} {"title": "Form Objects", "text": "node247.html\nnode244.html\nnode245.html\nnode1.html\nnode270.html\n---\n## Form Objects\nForm objects (returned by fl.make_form() above) have the\nfollowing methods. Each method corresponds to a C function whose name\nis prefixed with `fl_'; and whose first argument is a form\npointer; please refer to the official FORMS documentation for\ndescriptions.\nAll the `add_...' functions 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:\nName | Type | Meaning\n---\nnode247.html\nnode244.html\nnode245.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 760, "url": "https://docs.python.org/1.5/lib/node246.html"} {"title": "FORMS Objects", "text": "node248.html\nnode244.html\nnode246.html\nnode1.html\nnode270.html\n---\n## 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:\nName | Type | Meaning\n---\nguido@python.org", "python_version": "1.5", "length": 311, "url": "https://docs.python.org/1.5/lib/node247.html"} {"title": "16.5 Standard Module FL", "text": "node249.html\nnode238.html\nnode247.html\nnode1.html\nnode270.html\n---\n# 16.5 Standard Module FL\nThis module defines symbolic constants needed to use the built-in\nmodule fl (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\nimport fl\nfrom FL import *\n```\n---\nguido@python.org", "python_version": "1.5", "length": 437, "url": "https://docs.python.org/1.5/lib/node248.html"} {"title": "16.6 Standard Module flp", "text": "node250.html\nnode238.html\nnode248.html\nnode1.html\nnode270.html\n---\n# 16.6 Standard Module flp\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 above).\nFor now, see the file `flp.doc' in the Python library source\ndirectory for a description.\nXXX A complete description should be inserted here!\n---\nguido@python.org", "python_version": "1.5", "length": 423, "url": "https://docs.python.org/1.5/lib/node249.html"} {"title": "2.2 Built-in Exceptions", "text": "node26.html\nnode3.html\nnode24.html\nnode1.html\nnode270.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 the the same. The source code for those\nexceptions is present in the standard library module\nexceptions; this module never needs to be imported explicitly.\nFor backward compatibility, when Python is invoked with the -X\noption, the standard exceptions are strings. This may be needed to\nrun some code that breaks because of the different semantics of class\nbased exceptions. The -X option will become obsolete in future\nPython versions, so the recommended solution is to fix the code.\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 an except\nclause that mentions a particular class, that clause also handles\nany exception classes derived from that class (but not exception\nclasses from which it is derived). Two exception classes\nthat are not related via subclassing are never equivalent, even if\nthey 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 raise\nstatement. For string exceptions, the associated value itself will be\nstored in the variable named as the second argument of the\nexcept clause (if any). For class exceptions derived from\nthe root class Exception, that variable receives the exception\ninstance, and the associated value is present as the exception\ninstance's args attribute; this is a tuple even if the second\nargument to raise was not (then it is a singleton tuple).\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. When string-based standard exceptions are used, they\nare tuples containing the directly derived classes.\nThe following exceptions are the exceptions that are actually raised.\nThey are class objects, except when the -X option is used to\nrevert back to string-based standard exceptions.\n---\nnode26.html\nnode3.html\nnode24.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3043, "url": "https://docs.python.org/1.5/lib/node25.html"} {"title": "16.7 Built-in Module fm", "text": "node251.html\nnode238.html\nnode249.html\nnode1.html\nnode270.html\n---\n# 16.7 Built-in Module fm\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 the IRIS\nFont 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:\n---\nnode251.html\nnode238.html\nnode249.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 724, "url": "https://docs.python.org/1.5/lib/node250.html"} {"title": "16.8 Built-in Module gl", "text": "node252.html\nnode238.html\nnode250.html\nnode1.html\nnode270.html\n---\n# 16.8 Built-in Module gl\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.All float and double values are represented by Python floating point\nnumbers.\nIn most cases, Python integers are also allowed.All arrays are represented by one-dimensional Python lists.\nIn most cases, tuples are also allowed.All string and character arguments are represented by Python strings,\nfor instance,\nwinopen('Hi There!')\nand\nrotate(900, 'z').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\nlmdef(deftype, index, np, props)\n```\nis translated to Python as\n```text\nlmdef(deftype, index, props)\n```\nOutput 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\ngetmcolor(i, &red, &green, &blue)\n```\nis translated to Python as\n```text\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\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```\n---\nnode252.html\nnode238.html\nnode250.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2343, "url": "https://docs.python.org/1.5/lib/node251.html"} {"title": "16.9 Standard Modules GL and DEVICE", "text": "node253.html\nnode238.html\nnode251.html\nnode1.html\nnode270.html\n---\n# 16.9 Standard Modules GL and DEVICE\nThese modules define the constants used by the Silicon Graphics\nGraphics Library\nthat C programmers find in the header files\n`'\nand\n`'.\nRead the module source files for details.\n---\nguido@python.org", "python_version": "1.5", "length": 325, "url": "https://docs.python.org/1.5/lib/node252.html"} {"title": "16.10 Built-in Module imgfile", "text": "node254.html\nnode238.html\nnode252.html\nnode1.html\nnode270.html\n---\n# 16.10 Built-in Module imgfile\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:\n---\nnode254.html\nnode238.html\nnode252.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 509, "url": "https://docs.python.org/1.5/lib/node253.html"} {"title": "17 SunOS Specific Services", "text": "node255.html\nlib.html\nnode253.html\nnode1.html\nnode270.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).\n---\n- 17.1 Built-in Module sunaudiodev (node255.html#SECTION0018100000000000000000)\n- Audio Device Objects (node256.html#SECTION0018110000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 446, "url": "https://docs.python.org/1.5/lib/node254.html"} {"title": "17.1 Built-in Module sunaudiodev", "text": "node256.html\nnode254.html\nnode254.html\nnode1.html\nnode270.html\n---\n# 17.1 Built-in Module sunaudiodev\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 full\ndescription can be gotten with `man audio'.\nThe module defines the following variables and functions:\n---\n- Audio Device Objects (node256.html#SECTION0018110000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 489, "url": "https://docs.python.org/1.5/lib/node255.html"} {"title": "Audio Device Objects", "text": "node257.html\nnode255.html\nnode255.html\nnode1.html\nnode270.html\n---\n## Audio Device Objects\nThe audio device objects are returned by open define the\nfollowing methods (except control objects which only provide\ngetinfo, setinfo and drain):\nThere is a companion module, SUNAUDIODEV, which defines useful\nsymbolic constants like MIN_GAIN, MAX_GAIN,\nSPEAKER, etc. The names of\nthe constants are the same names as used in the C include file\n`', with the leading string `AUDIO_'\nstripped.\nUseability of the control device is limited at the moment, since there\nis no way to use the ``wait for something to happen'' feature the\ndevice provides.\n---\nnode257.html\nnode255.html\nnode255.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 734, "url": "https://docs.python.org/1.5/lib/node256.html"} {"title": "18 Undocumented Modules", "text": "node258.html\nlib.html\nnode256.html\nnode1.html\nnode270.html\n---\n# 18 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 most contents for this chapter were taken from a\nposting by Fredrik Lundh; I have revised some modules' status.)\n---\n- 18.1 Fundamental, and pretty straightforward to document (node258.html#SECTION0019100000000000000000)\n18.2 Frameworks; somewhat harder to document, but well worth the effort (node259.html#SECTION0019200000000000000000)\n18.3 Stuff useful to a lot of people, including the CGI crowd (node260.html#SECTION0019300000000000000000)\n18.4 Miscellaneous useful utilities (node261.html#SECTION0019400000000000000000)\n18.5 Parsing Python (node262.html#SECTION0019500000000000000000)\n18.6 Platform specific modules (node263.html#SECTION0019600000000000000000)\n18.7 Code objects and files, debugger etc. (node264.html#SECTION0019700000000000000000)\n18.8 Multimedia (node265.html#SECTION0019800000000000000000)\n18.9 Oddities (node266.html#SECTION0019900000000000000000)\n18.10 Obsolete (node267.html#SECTION00191000000000000000000)\n18.11 Extension modules (node268.html#SECTION00191100000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1275, "url": "https://docs.python.org/1.5/lib/node257.html"} {"title": "18.1 Fundamental, and pretty straightforward to document", "text": "node259.html\nnode257.html\nnode257.html\nnode1.html\nnode270.html\n---\n# 18.1 Fundamental, and pretty straightforward to document\ncPickle.c - mostly the same as pickle but no subclassing\ncStringIO.c - mostly the same as StringIO but no subclassing\n---\nguido@python.org", "python_version": "1.5", "length": 264, "url": "https://docs.python.org/1.5/lib/node258.html"} {"title": "18.2 Frameworks; somewhat harder to document, but well worth the effort", "text": "node260.html\nnode257.html\nnode258.html\nnode1.html\nnode270.html\n---\n# 18.2 Frameworks; somewhat harder to document, but well worth the effort\nTkinter.py - Interface to Tcl/Tk for graphical user interfaces;\nFredrik Lundh is working on this one!\nCGIHTTPServer.py - CGI-savvy HTTP Server\nSimpleHTTPServer.py - Simple HTTP Server\n---\nguido@python.org", "python_version": "1.5", "length": 345, "url": "https://docs.python.org/1.5/lib/node259.html"} {"title": "2.3 Built-in Functions", "text": "node27.html\nnode3.html\nnode25.html\nnode1.html\nnode270.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.\n---\nnode27.html\nnode3.html\nnode25.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 301, "url": "https://docs.python.org/1.5/lib/node26.html"} {"title": "18.3 Stuff useful to a lot of people, including the CGI crowd", "text": "node261.html\nnode257.html\nnode259.html\nnode1.html\nnode270.html\n---\n# 18.3 Stuff useful to a lot of people, including the CGI crowd\nMimeWriter.py - Generic MIME writer\nmultifile.py - make each part of a multipart message ``feel'' like\nfileinput.py - convenient loop over the lines in a list of input files.\n---\nguido@python.org", "python_version": "1.5", "length": 326, "url": "https://docs.python.org/1.5/lib/node260.html"} {"title": "18.4 Miscellaneous useful utilities", "text": "node262.html\nnode257.html\nnode260.html\nnode1.html\nnode270.html\n---\n# 18.4 Miscellaneous useful utilities\nSome of these are very old and/or not very robust; marked with ``hmm''.\ncalendar.py - Calendar printing functions\nConfigParser.py - Parse a file of sectioned configuration parameters\ncmp.py - Efficiently compare files\ncmpcache.py - Efficiently compare files (uses statcache)\ndircache.py - like os.listdir, but caches results\ndircmp.py - class to build directory diff tools on\nlinecache.py - Cache lines from files (used by pdb)\npipes.py - Conversion pipeline templates (hmm)\npopen2.py - improved popen, can read AND write simultaneously\nstatcache.py - Maintain a cache of file stats\ncolorsys.py - Conversion between RGB and other color systems\ndbhash.py - (g)dbm-like wrapper for bsdhash.hashopen\nmhlib.py - MH interface\npty.py - Pseudo terminal utilities\ntty.py - Terminal utilities\ncmd.py - build line-oriented command interpreters (used by pdb)\nbdb.py - A generic Python debugger base class (used by pdb)\nihooks.py - Import hook support (for ni and rexec)\n---\nguido@python.org", "python_version": "1.5", "length": 1084, "url": "https://docs.python.org/1.5/lib/node261.html"} {"title": "18.5 Parsing Python", "text": "node263.html\nnode257.html\nnode261.html\nnode1.html\nnode270.html\n---\n# 18.5 Parsing Python\n(One could argue that these should all be documented together with the\nparser module.)\ntokenize.py - regular expression that recognizes Python tokens; also\ncontains helper code for colorizing Python source code.\npyclbr.py - Parse a Python file and retrieve classes and methods\n---\nguido@python.org", "python_version": "1.5", "length": 386, "url": "https://docs.python.org/1.5/lib/node262.html"} {"title": "18.6 Platform specific modules", "text": "node264.html\nnode257.html\nnode262.html\nnode1.html\nnode270.html\n---\n# 18.6 Platform specific modules\nntpath.py - equivalent of posixpath on 32-bit Windows\ndospath.py - equivalent of posixpath on MS-DOS\n---\nguido@python.org", "python_version": "1.5", "length": 221, "url": "https://docs.python.org/1.5/lib/node263.html"} {"title": "18.7 Code objects and files, debugger etc.", "text": "node265.html\nnode257.html\nnode263.html\nnode1.html\nnode270.html\n---\n# 18.7 Code objects and files, debugger etc.\ncompileall.py - force \"compilation\" of all .py files in a directory\npy_compile.py - \"compile\" a .py file to a .pyc file\nrepr.py - Redo the `...` (representation) but with limits on most\nsizes (used by pdb)\n---\nguido@python.org", "python_version": "1.5", "length": 338, "url": "https://docs.python.org/1.5/lib/node264.html"} {"title": "18.8 Multimedia", "text": "node266.html\nnode257.html\nnode264.html\nnode1.html\nnode270.html\n---\n# 18.8 Multimedia\naudiodev.py - Plays audio files\nsunau.py - parse Sun and NeXT audio files\nsunaudio.py - interpret sun audio headers\ntoaiff.py - Convert \"arbitrary\" sound files to AIFF files\nsndhdr.py - recognizing sound files\nwave.py - parse WAVE files\nwhatsound.py - recognizing sound files\n---\nguido@python.org", "python_version": "1.5", "length": 381, "url": "https://docs.python.org/1.5/lib/node265.html"} {"title": "18.9 Oddities", "text": "node267.html\nnode257.html\nnode265.html\nnode1.html\nnode270.html\n---\n# 18.9 Oddities\nThese modules are probably also obsolete, or just not very useful.\nbisect.py - Bisection algorithms (this is actually useful at times)\ndump.py - Print python code that reconstructs a variable\nfind.py - find files matching pattern in directory tree\nfpformat.py - General floating point formatting functions - obsolete\ngrep.py - grep\nmutex.py - Mutual exclusion - for use with module sched\npackmail.py - create a self-unpacking Unix shell archive\npoly.py - Polynomials\nsched.py - event scheduler class\nshutil.py - utility functions usable in a shell-like program\nutil.py - useful functions that don't fit elsewhere\nzmod.py - Compute properties of mathematical \"fields\"\ntzparse.py - Parse a timezone specification (unfinished)\n---\nguido@python.org", "python_version": "1.5", "length": 827, "url": "https://docs.python.org/1.5/lib/node266.html"} {"title": "18.10 Obsolete", "text": "node268.html\nnode257.html\nnode266.html\nnode1.html\nnode270.html\n---\n# 18.10 Obsolete\nnewdir.py - New dir() function (the standard dir() is now just as good)\naddpack.py - standard support for \"packages\" (use ni instead)\nfmt.py - text formatting abstractions (too slow)\nPara.py - helper for fmt.py\nlockfile.py - wrapper around FCNTL file locking (use\nfcntl.lockf/flock intead)\ntb.py - Print tracebacks, with a dump of local variables (use\npdb.pm() or traceback.py instead)\ncodehack.py - extract function name or line number from a function\ncode object (these are now accessible as attributes: co.co_name,\nfunc.func_name, co.co_firstlineno)\n---\nguido@python.org", "python_version": "1.5", "length": 657, "url": "https://docs.python.org/1.5/lib/node267.html"} {"title": "18.11 Extension modules", "text": "node269.html\nnode257.html\nnode267.html\nnode1.html\nnode270.html\n---\n# 18.11 Extension modules\nbsddbmodule.c - Interface to the Berkeley DB interface (yet another\ndbm clone).\ncursesmodule.c - Curses interface.\ndbhashmodule.c - Obsolete; this functionality is now provided by\nbsddbmodule.c.\ndlmodule.c - A highly experimental and dangerous device for calling\narbitrary C functions in arbitrary shared libraries.\nnewmodule.c - Tommy Burnette's `new' module (creates new empty\nobjects of certain kinds) - dangerous.\nnismodule.c - NIS (a.k.a. Sun's Yellow Pages) interface.\ntimingmodule.c - Measure time intervals to high resolution (obsolete\n- use time.clock() instead).\nstdwinmodule.c - Interface to STDWIN (an old, unsupported\nplatform-independent GUI package). Obsolete; use Tkinter for a\nplatform-independent GUI instead.\nThe following are SGI specific:\nclmodule.c - Interface to the SGI compression library.\nsvmodule.c - Interface to the ``simple video'' board on SGI Indigo\n(obsolete hardware).\n---\nguido@python.org", "python_version": "1.5", "length": 1016, "url": "https://docs.python.org/1.5/lib/node268.html"} {"title": "Module Index", "text": "node270.html\nlib.html\nnode268.html\nnode1.html\nnode270.html\n---\n## Module Index\n__builtin__ (node60.html#3956)\n__main__ (node61.html#3963)\naifc (node195.html#12306)\nal (node239.html#14093)\nAL (node242.html#14217)\nanydbm (node101.html#7149)\narray (node82.html#5539)\naudioop (node193.html#12051)\nbase64 (node181.html#11349)\nBaseHTTPServer (node187.html#11642)\nBastion (node191.html#12022)\nbinascii (node175.html#11055)\nbinhex (node172.html#11003)\ncd (node243.html#14226)\ncgi (node140.html#9159)\nCGIHTTPServer (node187.html#11653)\ncmath (node78.html#5282)\ncode (node53.html#3289)\ncommands (node123.html#8758)\ncopy (node36.html#2696)\ncopy_reg (node34.html#2649)\ncrypt (node110.html#8053)\nctb (node206.html#12821)\ndbm (node111.html#8072)\nDEVICE (node252.html#15090)\ndis (node56.html#3393)\ndumbdbm (node101.html#7150)\nEasyDialogs (node229.html#13784)\nerrno (node88.html#5993)\nexceptions (node25.html#1118)\nfcntl (node116.html#8264)\nfindertools (node221.html#13522)\nfl (node244.html#14451)\nFL (node248.html#14909)\nflp (node249.html#14915)\nfm (node250.html#14927)\nfnmatch (node90.html#6394)\nformatter (node163.html#10524)\nFrameWork (node230.html#13822)\nftplib (node154.html#9479)\ngdbm (node112.html#8105)\ngetopt (node86.html#5930)\ngl (node251.html#15013)\nGL (node252.html#15089)\nglob (node89.html#6368)\ngopherlib (node156.html#9670)\ngrp (node109.html#8028)\ngzip (node104.html#7278)\nhtmllib (node161.html#10219)\nhttplib (node151.html#9397)\nic (node217.html#13321)\nimageop (node194.html#12231)\nimgfile (node253.html#15106)\nimghdr (node198.html#12530)\nimp (node38.html#2779)\njpeg (node196.html#12454)\nkeyword (node52.html#3280)\nlocale (node91.html#6440)\nmac (node204.html#12775)\nmacconsole (node208.html#12957)\nmacdnr (node211.html#13060)\nmacfs (node213.html#13138)\nMacOS (node219.html#13428)\nmacostools (node220.html#13484)\nmacpath (node205.html#12801)\nmacspeech (node226.html#13714)\nmactcp (node222.html#13566)\nmailbox (node184.html#11558)\nmailcap (node180.html#11313)\nmarshal (node37.html#2725)\nmath (node77.html#5132)\nmd5 (node200.html#12569)\nmimetools (node170.html#10887)\nmimify (node186.html#11585)\nMiniAEFrame (node236.html#14043)\nmpz (node201.html#12612)\nni (node40.html#2973)\nnntplib (node157.html#9702)\noperator (node31.html#2140)\nos (node84.html#5677)\nparser (node41.html#3011)\npdb (node124.html#8791)\npickle (node33.html#2507)\nposix (node106.html#7342)\nposixfile (node117.html#8331)\nposixpath (node107.html#7829)\npprint (node54.html#3314)\nprofile (node127.html#8939)\npstats (node127.html#8940)\npwd (node108.html#8000)\nQueue (node99.html#7095)\nquopri (node182.html#11393)\nrand (node81.html#5512)\nrandom (node80.html#5429)\nre (node64.html#4244)\nregex (node69.html#4684)\nregsub (node72.html#4910)\nresource (node118.html#8464)\nrexec (node189.html#11823)\nrfc822 (node168.html#10767)\nrgbimg (node197.html#12493)\nrotor (node202.html#12712)\nselect (node97.html#6985)\nsgmllib (node160.html#10036)\nshelve (node35.html#2676)\nsignal (node93.html#6585)\nSimpleHTTPServer (node187.html#11652)\nsite (node58.html#3869)\nsocket (node94.html#6679)\nSocketServer (node183.html#11425)\nsoundex (node75.html#5107)\nstat (node122.html#8687)\nstring (node63.html#3970)\nStringIO (node74.html#5095)\nstruct (node73.html#4974)\nsunaudiodev (node255.html#15162)\nsymbol (node50.html#3220)\nsys (node28.html#1839)\nsyslog (node121.html#8609)\ntempfile (node87.html#5952)\nTERMIOS (node115.html#8246)\ntermios (node113.html#8167)\nthread (node98.html#7019)\ntime (node85.html#5796)\ntoken (node51.html#3232)\ntraceback (node32.html#2442)\ntypes (node29.html#2010)\nurllib (node150.html#9305)\nurlparse (node159.html#9991)\nuser (node59.html#3926)\nUserDict (node30.html#2111)\nUserList (node30.html#2112)\nuu (node174.html#11027)\nwhichdb (node102.html#7178)\nwhrandom (node79.html#5380)\nxdrlib (node176.html#11119)\nxmllib (node162.html#10321)\nzlib (node103.html#7191)\n---\nguido@python.org", "python_version": "1.5", "length": 3834, "url": "https://docs.python.org/1.5/lib/node269.html"} {"title": "3 Python Services", "text": "node28.html\nlib.html\nnode26.html\nnode1.html\nnode270.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:\n---\n- 3.1 Built-in Module sys (node28.html#SECTION004100000000000000000)\n3.2 Standard Module types (node29.html#SECTION004200000000000000000)\n3.3 Standard Modules UserDict and UserList (node30.html#SECTION004300000000000000000)\n3.4 Built-in Module operator (node31.html#SECTION004400000000000000000)\n3.5 Standard Module traceback (node32.html#SECTION004500000000000000000)\n3.6 Standard Module pickle (node33.html#SECTION004600000000000000000)\nStandard Module copy_reg (node34.html#SECTION004700000000000000000)\n3.8 Standard Module shelve (node35.html#SECTION004800000000000000000)\n3.9 Standard Module copy (node36.html#SECTION004900000000000000000)\n3.10 Built-in Module marshal (node37.html#SECTION0041000000000000000000)\n3.11 Built-in Module imp (node38.html#SECTION0041100000000000000000)\n- Examples (node39.html#SECTION0041110000000000000000)\n3.12 Standard Module ni (node40.html#SECTION0041200000000000000000)\n3.13 Built-in Module parser (node41.html#SECTION0041300000000000000000)\n- Creating AST Objects (node42.html#SECTION0041310000000000000000)\nConverting AST Objects (node43.html#SECTION0041320000000000000000)\nQueries on AST Objects (node44.html#SECTION0041330000000000000000)\nExceptions and Error Handling (node45.html#SECTION0041340000000000000000)\nAST Objects (node46.html#SECTION0041350000000000000000)\nExamples (node47.html#SECTION0041360000000000000000)\n- Emulation of compile() (node48.html#SECTION0041361000000000000000)\nInformation Discovery (node49.html#SECTION0041362000000000000000)\n3.14 Standard Module symbol (node50.html#SECTION0041400000000000000000)\n3.15 Standard Module token (node51.html#SECTION0041500000000000000000)\n3.16 Standard Module keyword (node52.html#SECTION0041600000000000000000)\n3.17 Standard Module code (node53.html#SECTION0041700000000000000000)\n3.18 Standard Module pprint (node54.html#SECTION0041800000000000000000)\n- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)\n3.19 Standard Module dis (node56.html#SECTION0041900000000000000000)\n- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)\n3.20 Standard Module site (node58.html#SECTION0042000000000000000000)\n3.21 Standard Module user (node59.html#SECTION0042100000000000000000)\nBuilt-in Module __builtin__ (node60.html#SECTION0042200000000000000000)\nBuilt-in Module __main__ (node61.html#SECTION0042300000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2625, "url": "https://docs.python.org/1.5/lib/node27.html"} {"title": "About this document ...", "text": "lib.html\nnode270.html\nnode1.html\nnode270.html\n---\n# About this document ...\nPython Library Reference\nThis document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.\nThe command line arguments were:\nlatex2html -address guido@python.org lib.tex.\nThe translation was initiated by Fred L. Drake on Tue Feb 17 10:28:55 EST 1998\n---\nguido@python.org", "python_version": "1.5", "length": 578, "url": "https://docs.python.org/1.5/lib/node271.html"} {"title": "3.1 Built-in Module sys", "text": "node29.html\nnode27.html\nnode27.html\nnode1.html\nnode270.html\n---\n# 3.1 Built-in Module sys\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.\n---\nnode29.html\nnode27.html\nnode27.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 340, "url": "https://docs.python.org/1.5/lib/node28.html"} {"title": "3.2 Standard Module types", "text": "node30.html\nnode27.html\nnode28.html\nnode1.html\nnode270.html\n---\n# 3.2 Standard Module 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 other names besides the ones listed\nhere. New names exported by future versions of this module will\nall end in Type.\nTypical use is for functions that do different things depending on\ntheir argument types, like the following:\n```text\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:\n---\nnode30.html\nnode27.html\nnode28.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 793, "url": "https://docs.python.org/1.5/lib/node29.html"} {"title": "2 Built-in Types, Exceptions and Functions", "text": "node4.html\nlib.html\nnode2.html\nnode1.html\nnode270.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.footnode.html#27\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 Reference Manual for the\ncomplete picture on operator priorities.\n---\n- 2.1 Built-in Types (node4.html#SECTION003100000000000000000)\n- Truth Value Testing (node5.html#SECTION003110000000000000000)\nBoolean Operations (node6.html#SECTION003120000000000000000)\nComparisons (node7.html#SECTION003130000000000000000)\nNumeric Types (node8.html#SECTION003140000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)\nSequence Types (node10.html#SECTION003150000000000000000)\n- More String Operations (node11.html#SECTION003151000000000000000)\nMutable Sequence Types (node12.html#SECTION003152000000000000000)\nMapping Types (node13.html#SECTION003160000000000000000)\nOther Built-in Types (node14.html#SECTION003170000000000000000)\n- Modules (node15.html#SECTION003171000000000000000)\nClasses and Class Instances (node16.html#SECTION003172000000000000000)\nFunctions (node17.html#SECTION003173000000000000000)\nMethods (node18.html#SECTION003174000000000000000)\nCode Objects (node19.html#SECTION003175000000000000000)\nType Objects (node20.html#SECTION003176000000000000000)\nThe Null Object (node21.html#SECTION003177000000000000000)\nFile Objects (node22.html#SECTION003178000000000000000)\nInternal Objects (node23.html#SECTION003179000000000000000)\nSpecial Attributes (node24.html#SECTION003180000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION003200000000000000000)\n2.3 Built-in Functions (node26.html#SECTION003300000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2275, "url": "https://docs.python.org/1.5/lib/node3.html"} {"title": "3.3 Standard Modules UserDict and UserList", "text": "node31.html\nnode27.html\nnode29.html\nnode1.html\nnode270.html\n---\n# 3.3 Standard Modules UserDict and UserList\nEach of these modules defines a class that acts as a wrapper around\neither dictionary or list objects. They're useful base classes for\nyour own dictionary-like or 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 dictionaries or lists.\nThe UserDict module defines the UserDict class:\nThe UserList module defines the UserList class:\n---\nguido@python.org", "python_version": "1.5", "length": 547, "url": "https://docs.python.org/1.5/lib/node30.html"} {"title": "3.4 Built-in Module operator", "text": "node32.html\nnode27.html\nnode30.html\nnode1.html\nnode270.html\n---\n# 3.4 Built-in Module operator\nThe operator module exports a set of functions implemented in C\ncorresponding to the intrinsic operators of Python. For example,\noperator.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\n256 to their character equivalents.\n```text\n>>> import operator\n>>> d = {}\n>>> keys = range(256)\n>>> vals = map(chr, keys)\n>>> map(operator.setitem, [d]*len(keys), keys, vals)\n```\n---\nnode32.html\nnode27.html\nnode30.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 793, "url": "https://docs.python.org/1.5/lib/node31.html"} {"title": "3.5 Standard Module traceback", "text": "node33.html\nnode27.html\nnode31.html\nnode1.html\nnode270.html\n---\n# 3.5 Standard Module traceback\nThis module provides a standard interface to format and print stack\ntraces of Python programs. It exactly mimics the behavior of the\nPython interpreter when it prints a stack trace. This is useful when\nyou 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\nsys.last_traceback.\nThe module defines the following functions:\n---\nnode33.html\nnode27.html\nnode31.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 657, "url": "https://docs.python.org/1.5/lib/node32.html"} {"title": "3.6 Standard Module pickle", "text": "node34.html\nnode27.html\nnode32.html\nnode1.html\nnode270.html\n---\n# 3.6 Standard Module pickle\nThe pickle module implements a basic but powerful algorithm for\n``pickling'' (a.k.a. serializing, marshalling or flattening) nearly\narbitrary Python objects. This is the act of converting objects to a\nstream of bytes (and back: ``unpickling'').\nThis is a more primitive notion than\npersistency -- although pickle reads and writes file objects,\nit does not handle the issue of naming persistent objects, nor the\n(even more complicated) area of concurrent access to persistent\nobjects. The pickle module can transform a complex object into\na byte stream and it can transform the byte stream into an object with\nthe same internal structure. The most obvious thing to do with these\nbyte streams is to write them onto a file, but it is also conceivable\nto send them across a network or store them in a database. The module\nshelve provides a simple interface to pickle and unpickle\nobjects 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 cPickle\nmodule. This has the same interface except that Pickler and\nUnpickler are factory functions, not classes (so they cannot be\nused as a base class for inheritance).\nUnlike the built-in module marshal, pickle handles the\nfollowing correctly:\n- recursive objects (objects containing references to themselves)object sharing (references to the same object in different places)user-defined classes and their instances\nThe data format used by pickle is Python-specific. This has\nthe advantage that there are no restrictions imposed by external\nstandards such as XDR\n(which can't represent pointer sharing); however\nit means that non-Python programs may not be able to reconstruct\npickled 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 does. I suppose pickle could, and maybe\nit should, but there's probably no great need for it right now (as\nlong as marshal continues to be used for reading and writing\ncode objects), and at least this avoids the possibility of smuggling\nTrojan 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 the 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 copy\nmodule.\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\np = pickle.Pickler(f)\np.dump(x)\n```\nA shorthand for this is:\n```text\npickle.dump(x, f)\n```\nTo unpickle an object x from a file f, open for reading:\n```text\nu = pickle.Unpickler(f)\nx = u.load()\n```\nA shorthand is:\n```text\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()\n(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 nonzero, the binary\npickle format is used; if it is zero or absent, 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- Noneintegers, long integers, floating point numbersstringstuples, lists and dictionaries containing only picklable objectsclasses that are defined at the top level in a moduleinstances 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() instance 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:\n---\nnode34.html\nnode27.html\nnode32.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 8442, "url": "https://docs.python.org/1.5/lib/node33.html"} {"title": "Standard Module copy_reg", "text": "node35.html\nnode27.html\nnode33.html\nnode1.html\nnode270.html\n---\n# Standard Module copy_reg\nThe copy_reg module provides support for the\npickle and\ncPickle modules. The\ncopy 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.\n---\nguido@python.org", "python_version": "1.5", "length": 395, "url": "https://docs.python.org/1.5/lib/node34.html"} {"title": "3.8 Standard Module shelve", "text": "node36.html\nnode27.html\nnode34.html\nnode1.html\nnode270.html\n---\n# 3.8 Standard Module shelve\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 can handle. This includes most class instances,\nrecursive 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\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 (e.g. dbm or\ngdbm)\ndepends on which interface is available. Therefore it isn't safe to\nopen the database directly using dbm. The database is also\n(unfortunately) subject to the limitations of dbm, if it is used --\nthis means that (the pickled representation of) the objects stored in\nthe database should be fairly small, and in rare cases key collisions\nmay cause the database to refuse updates.\nDependent on the implementation, closing a persistent dictionary may\nor may not be necessary to flush changes to disk.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.\n---\nguido@python.org", "python_version": "1.5", "length": 1967, "url": "https://docs.python.org/1.5/lib/node35.html"} {"title": "3.9 Standard Module copy", "text": "node37.html\nnode27.html\nnode35.html\nnode1.html\nnode270.html\n---\n# 3.9 Standard Module copy\nThis module provides generic (shallow and deep) copying operations.\nInterface summary:\n```text\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.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.Because deep copy copies everything it may copy too much, e.g.\\\nadministrative data structures that should be shared even between\ncopies.\nPython's deepcopy() operation avoids these problems by:\n- keeping a table of objects already copied during the current\ncopying pass; andletting user-defined classes override the copying operation or the\nset of components copied.\nThis version does not copy types like module, class, function, method,\nnor stack trace, stack frame, nor file, socket, window, nor array, nor\nany similar types.\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 pickle\nfor information on these methods.\n---\nguido@python.org", "python_version": "1.5", "length": 1796, "url": "https://docs.python.org/1.5/lib/node36.html"} {"title": "3.10 Built-in Module marshal", "text": "node38.html\nnode27.html\nnode36.html\nnode1.html\nnode270.html\n---\n# 3.10 Built-in Module marshal\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 does).footnode.html#2726\nThis is not a general ``persistency'' module. For general persistency\nand transfer of Python objects through RPC calls, see the modules\npickle and shelve. 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:\nNone, integers, long integers, floating point numbers,\nstrings, tuples, lists, dictionaries, and code objects, where it\nshould be understood that tuples, lists and dictionaries are only\nsupported as long as the values contained therein are themselves\nsupported; and recursive lists and dictionaries should not be written\n(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.footnode.html#2775\nThere are functions that read/write files as well as functions\noperating on strings.\nThe module defines these functions:\n---\nnode38.html\nnode27.html\nnode36.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2083, "url": "https://docs.python.org/1.5/lib/node37.html"} {"title": "3.11 Built-in Module imp", "text": "node39.html\nnode27.html\nnode37.html\nnode1.html\nnode270.html\n---\n# 3.11 Built-in Module imp\nThis module provides an interface to the mechanisms used to implement\nthe import statement. It defines the following constants and\nfunctions:\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:\n---\n- Examples (node39.html#SECTION0041110000000000000000)\n---\nnode39.html\nnode27.html\nnode37.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 671, "url": "https://docs.python.org/1.5/lib/node38.html"} {"title": "Examples", "text": "node40.html\nnode38.html\nnode38.html\nnode1.html\nnode270.html\n---\n## 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\nimp.find_module() has been extended and\nimp.load_module() has been added in 1.4.)\n```text\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```\nA more complete example that implements hierarchical module names and\nincludes a reload() function can be found in the standard\nmodule knee (which is intended as an\nexample only - don't rely on any part of it being a standard\ninterface).\n---\nguido@python.org", "python_version": "1.5", "length": 1127, "url": "https://docs.python.org/1.5/lib/node39.html"} {"title": "2.1 Built-in Types", "text": "node5.html\nnode3.html\nnode3.html\nnode1.html\nnode270.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 conversion is\nimplicitly used when an object is written by the print statement.\n---\n- Truth Value Testing (node5.html#SECTION003110000000000000000)\nBoolean Operations (node6.html#SECTION003120000000000000000)\nComparisons (node7.html#SECTION003130000000000000000)\nNumeric Types (node8.html#SECTION003140000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)\nSequence Types (node10.html#SECTION003150000000000000000)\n- More String Operations (node11.html#SECTION003151000000000000000)\nMutable Sequence Types (node12.html#SECTION003152000000000000000)\nMapping Types (node13.html#SECTION003160000000000000000)\nOther Built-in Types (node14.html#SECTION003170000000000000000)\n- Modules (node15.html#SECTION003171000000000000000)\nClasses and Class Instances (node16.html#SECTION003172000000000000000)\nFunctions (node17.html#SECTION003173000000000000000)\nMethods (node18.html#SECTION003174000000000000000)\nCode Objects (node19.html#SECTION003175000000000000000)\nType Objects (node20.html#SECTION003176000000000000000)\nThe Null Object (node21.html#SECTION003177000000000000000)\nFile Objects (node22.html#SECTION003178000000000000000)\nInternal Objects (node23.html#SECTION003179000000000000000)\nSpecial Attributes (node24.html#SECTION003180000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1819, "url": "https://docs.python.org/1.5/lib/node4.html"} {"title": "3.12 Standard Module ni", "text": "node41.html\nnode27.html\nnode39.html\nnode1.html\nnode270.html\n---\n# 3.12 Standard Module ni\nWarning: This module is obsolete. As of Python 1.5a4,\npackage support (with different semantics for __init__ and no\nsupport for __domain__ or __) is built in the\ninterpreter. The ni module is retained only for backward\ncompatibility. As of Python 1.5b2, it has been renamed to ni1;\nif you really need it, you can use import ni1, but the\nrecommended approach is to rely on the built-in package support,\nconverting existing packages if needed. Note that mixing ni\nand the built-in package support doesn't work: once you import\nni, all packages use it.\nThe ni module defines a new importing scheme, which supports\npackages containing several Python modules. To enable package\nsupport, execute import ni before importing any packages. Importing\nthis module automatically installs the relevant import hooks. There\nare no publicly-usable functions or variables in the ni module.\nTo create a package named spam containing sub-modules ham, bacon and\neggs, create a directory `spam' somewhere on Python's module search\npath, as given in sys.path. Then, create files called `ham.py', `bacon.py' and\n`eggs.py' inside `spam'.\nTo import module ham from package spam and use function\nhamneggs() from that module, you can use any of the following\npossibilities:\n```text\nimport spam.ham # *not* \"import spam\" !!!\nspam.ham.hamneggs()\n```\n```text\nfrom spam import ham\nham.hamneggs()\n```\n```text\nfrom spam.ham import hamneggs\nhamneggs()\n```\nimport spam creates an\nempty package named spam if one does not already exist, but it does\nnot automatically import spam's submodules.\nThe only submodule that is guaranteed to be imported is\nspam.__init__, if it exists; it would be in a file named\n`__init__.py' in the `spam' directory. Note that\nspam.__init__ is a submodule of package spam. It can refer to\nspam's namespace as __ (two underscores):\n```text\n__.spam_inited = 1 # Set a package-level variable\n```\nAdditional initialization code (setting up variables, importing other\nsubmodules) can be performed in `spam/__init__.py'.\n---\nguido@python.org", "python_version": "1.5", "length": 2117, "url": "https://docs.python.org/1.5/lib/node40.html"} {"title": "3.13 Built-in Module parser", "text": "node42.html\nnode27.html\nnode40.html\nnode1.html\nnode270.html\n---\n# 3.13 Built-in Module parser\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 Language Reference. The\nparser itself is created from a grammar specification defined in the file\n`Grammar/Grammar' in the standard Python distribution. The parse\ntrees stored in the ``AST objects'' created by this module are the\nactual output from the internal parser when created by the\nexpr() or suite() functions, described below. The AST\nobjects created by sequence2ast() faithfully simulate those\nstructures. Be aware that the values of the sequences which are\nconsidered ``correct'' will vary from one version of Python to another\nas the formal grammar for the language is revised. However,\ntransporting code from one Python version to another as source text\nwill always allow correct parse trees to be created in the target\nversion, with the only restriction being that migrating to an older\nversion of the interpreter will not support more recent language\nconstructs. The parse trees are not typically compatible from one\nversion to another, whereas source code has always been\nforward-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. Each additional element of the sequence represents\na component of the production as recognized in the input string: these\nare always sequences which have the same form as the parent. An\nimportant aspect of this structure which should be noted is that\nkeywords used to identify the parent node type, such as the keyword\nif in an if_stmt, are included in the node tree without\nany special treatment. For example, the if keyword is\nrepresented by the tuple (1, 'if'), where 1 is the\nnumeric value associated with all NAME tokens, including\nvariable and function names defined by the user. In an alternate form\nreturned when line number information is requested, the same token\nmight be represented as (1, 'if', 12), where the 12\nrepresents the line number at which the terminal symbol was found.\nTerminal elements are represented in much the same way, but without\nany child elements and the addition of the source text which was\nidentified. The example of the if keyword above is\nrepresentative. The various types of terminal symbols are defined in\nthe C header file `Include/token.h' and the Python module\ntoken.\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.\n---\n- Creating AST Objects (node42.html#SECTION0041310000000000000000)\nConverting AST Objects (node43.html#SECTION0041320000000000000000)\nQueries on AST Objects (node44.html#SECTION0041330000000000000000)\nExceptions and Error Handling (node45.html#SECTION0041340000000000000000)\nAST Objects (node46.html#SECTION0041350000000000000000)\nExamples (node47.html#SECTION0041360000000000000000)\n- Emulation of compile() (node48.html#SECTION0041361000000000000000)\nInformation Discovery (node49.html#SECTION0041362000000000000000)\n---\nnode42.html\nnode27.html\nnode40.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 4852, "url": "https://docs.python.org/1.5/lib/node41.html"} {"title": "Creating AST Objects", "text": "node43.html\nnode41.html\nnode41.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode43.html\nnode41.html\nnode41.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 343, "url": "https://docs.python.org/1.5/lib/node42.html"} {"title": "Converting AST Objects", "text": "node44.html\nnode41.html\nnode42.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode44.html\nnode41.html\nnode42.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 420, "url": "https://docs.python.org/1.5/lib/node43.html"} {"title": "Queries on AST Objects", "text": "node45.html\nnode41.html\nnode43.html\nnode1.html\nnode270.html\n---\n## Queries on AST Objects\nTwo functions are provided which allow an application to determine if\nan AST was create 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().\n---\nguido@python.org", "python_version": "1.5", "length": 381, "url": "https://docs.python.org/1.5/lib/node44.html"} {"title": "Exceptions and Error Handling", "text": "node46.html\nnode41.html\nnode44.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nguido@python.org", "python_version": "1.5", "length": 727, "url": "https://docs.python.org/1.5/lib/node45.html"} {"title": "AST Objects", "text": "node47.html\nnode41.html\nnode45.html\nnode1.html\nnode270.html\n---\n## AST Objects\nAST objects returned by expr(), suite(), and\nsequence2ast() have no methods of their own.\nSome of the functions defined which accept an AST object as their\nfirst argument may change to object methods in the future. The type\nof these objects is available as ASTType in the module.\nOrdered and equality comparisons are supported between AST objects.\n---\nguido@python.org", "python_version": "1.5", "length": 447, "url": "https://docs.python.org/1.5/lib/node46.html"} {"title": "Examples", "text": "node48.html\nnode41.html\nnode46.html\nnode1.html\nnode270.html\n---\n## 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.\n---\n- Emulation of compile() (node48.html#SECTION0041361000000000000000)\nInformation Discovery (node49.html#SECTION0041362000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 630, "url": "https://docs.python.org/1.5/lib/node47.html"} {"title": "Emulation of compile()", "text": "node49.html\nnode47.html\nnode47.html\nnode1.html\nnode270.html\n---\n### 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 equivelent to the code\n```text\n>>> code = compile('a + 5', 'eval')\n>>> a = 5\n>>> eval(code)\n10\n```\nThe equivelent 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>>> import parser\n>>> ast = parser.expr('a + 5')\n>>> code = parser.compileast(ast)\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\nimport parser\n\ndef load_suite(source_string):\nast = parser.suite(source_string)\ncode = parser.compileast(ast)\nreturn ast, code\n\ndef load_expression(source_string):\nast = parser.expr(source_string)\ncode = parser.compileast(ast)\nreturn ast, code\n```\n---\nguido@python.org", "python_version": "1.5", "length": 1061, "url": "https://docs.python.org/1.5/lib/node48.html"} {"title": "Information Discovery", "text": "node50.html\nnode47.html\nnode48.html\nnode1.html\nnode270.html\n---\n### 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 docstrings without requiring\nthat the code being examined be loaded into a running interpreter via\nimport. This can be very useful for performing analyses of\nuntrusted 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\n`Demo/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\n`docstring.py'.)\n```text\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>>> import parser\n>>> import pprint\n>>> ast = parser.suite(open('docstring.py').read())\n>>> tup = parser.ast2tuple(ast)\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 and token 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 equivelence 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\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\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>>> 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\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\ndef square(x): \"Square an argument.\"; return x ** 2\n```\nwhile the long form uses an indented block and allows nested\ndefinitions:\n```text\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\ndef get_docs(fileName):\nsource = open(fileName).read()\nimport os\nbasename = os.path.basename(os.path.splitext(fileName)[0])\nimport parser\nast = parser.suite(source)\ntup = parser.ast2tuple(ast)\nreturn ModuleInfo(tup, basename)\n```\nThis provides an easy-to-use interface to the documentation of a\nmodule. If information is required which is not extracted by the code\nof this example, the code may be extended at clearly defined points to\nprovide additional capabilities.\nSee Also:\nsymbol (useful constants representing internal nodes of the parse tree)\ntoken (useful constants representing leaf nodes of the parse tree and\nfunctions for testing node values)\n---\nnode50.html\nnode47.html\nnode48.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 13695, "url": "https://docs.python.org/1.5/lib/node49.html"} {"title": "Truth Value Testing", "text": "node6.html\nnode4.html\nnode4.html\nnode1.html\nnode270.html\n---\n## 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\nzero of any numeric type, e.g., 0, 0L, 0.0.any empty sequence, e.g., '', (), [].any empty mapping, e.g., {}.instances of user-defined classes, if the class defines a\n__nonzero__() or __len__() method, when that\nmethod returns zero.\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.)\n---\nguido@python.org", "python_version": "1.5", "length": 819, "url": "https://docs.python.org/1.5/lib/node5.html"} {"title": "3.14 Standard Module symbol", "text": "node51.html\nnode27.html\nnode49.html\nnode1.html\nnode270.html\n---\n# 3.14 Standard Module symbol\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:\nSee Also:\nparser (second example uses this module)\n---\nguido@python.org", "python_version": "1.5", "length": 602, "url": "https://docs.python.org/1.5/lib/node50.html"} {"title": "3.15 Standard Module token", "text": "node52.html\nnode27.html\nnode50.html\nnode1.html\nnode270.html\n---\n# 3.15 Standard Module token\nThis module provides constants which represent the numeric values of\nleaf nodes of the parse tree (terminal tokens). Refer to the file\n`Grammar/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.\nSee Also:\nparser (second example uses this module)\n---\nguido@python.org", "python_version": "1.5", "length": 628, "url": "https://docs.python.org/1.5/lib/node51.html"} {"title": "3.16 Standard Module keyword", "text": "node53.html\nnode27.html\nnode51.html\nnode1.html\nnode270.html\n---\n# 3.16 Standard Module keyword\nThis module allows a Python program to determine if a string is a\nkeyword. A single function is provided:\n---\nguido@python.org", "python_version": "1.5", "length": 221, "url": "https://docs.python.org/1.5/lib/node52.html"} {"title": "3.17 Standard Module code", "text": "node54.html\nnode27.html\nnode52.html\nnode1.html\nnode270.html\n---\n# 3.17 Standard Module code\nThe code module defines operations pertaining to Python code\nobjects.\nThe code module defines the following functions:\n%\n---\nguido@python.org", "python_version": "1.5", "length": 233, "url": "https://docs.python.org/1.5/lib/node53.html"} {"title": "3.18 Standard Module pprint", "text": "node55.html\nnode27.html\nnode53.html\nnode1.html\nnode270.html\n---\n# 3.18 Standard Module pprint\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 you need\nto 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---\n- PrettyPrinter Objects (node55.html#SECTION0041810000000000000000)\n---\nnode55.html\nnode27.html\nnode53.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1080, "url": "https://docs.python.org/1.5/lib/node54.html"} {"title": "PrettyPrinter Objects", "text": "node56.html\nnode54.html\nnode54.html\nnode1.html\nnode270.html\n---\n## PrettyPrinter Objects\nPrettyPrinter instances (returned by PrettyPrinter() above)\nhave 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 objects\ndon't need to be created.\n---\nguido@python.org", "python_version": "1.5", "length": 418, "url": "https://docs.python.org/1.5/lib/node55.html"} {"title": "3.19 Standard Module dis", "text": "node57.html\nnode27.html\nnode55.html\nnode1.html\nnode270.html\n---\n# 3.19 Standard Module dis\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\n`Include/opcode.h' and used by the compiler and the interpreter.\nExample: Given the function myfunc\n```text\ndef myfunc(alist):\nreturn len(alist)\n```\nthe following command can be used to get the disassembly of myfunc():\n```text\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:\n---\n- Python Byte Code Instructions (node57.html#SECTION0041910000000000000000)\n---\nnode57.html\nnode27.html\nnode55.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 943, "url": "https://docs.python.org/1.5/lib/node56.html"} {"title": "Python Byte Code Instructions", "text": "node58.html\nnode56.html\nnode56.html\nnode1.html\nnode270.html\n---\n## 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.\n---\nnode58.html\nnode56.html\nnode56.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 794, "url": "https://docs.python.org/1.5/lib/node57.html"} {"title": "3.20 Standard Module site", "text": "node59.html\nnode27.html\nnode57.html\nnode1.html\nnode270.html\n---\n# 3.20 Standard Module site\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 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\nsys.exec_prefix; empty heads are skipped. For\nthe tail part, it uses the empty string (on Mac or Windows) or it uses\nfirst `lib/pythonversion/site-packages' and then\n`lib/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\n`package.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\nsys.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 , library is then\ninstalled in `/usr/local/lib/python,'. Suppose this has a\nsubdirectory `/usr/local/python,/site-packages' with three\nsubsubdirectories, `foo', `bar' and `spam', and two\npath configuration files, `foo.pth' and `bar.pth'. Assume\n`foo.pth' contains the following:\n```text\n# foo package configuration\n\nfoo\nbar\nbletch\n```\nand `bar.pth' contains:\n```text\n# bar package configuration\n\nbar\n```\nThen the following directories are added to sys.path, in this\norder:\n```text\n/usr/local/python1.5/site-packages/bar\n/usr/local/python1.5/site-packages/foo\n```\nNote that `bletch' is omitted because it doesn't exist; the\n`bar' directory precedes the `foo' directory because\n`bar.pth' comes alphabetically before `foo.pth'; and\n`spam' 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,sitecustomize, which can\nperform arbitrary site-specific customizations. If this import fails\nwith an ImportError exception, it is silently ignored.\nNote that for some non-Unix systems, sys.prefix and\nsys.exec_prefix are empty, and the path manipulations are\nskipped; however the import of\nsitecustomize,sitecustomize is still attempted.\n---\nnode59.html\nnode27.html\nnode57.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2700, "url": "https://docs.python.org/1.5/lib/node58.html"} {"title": "3.21 Standard Module user", "text": "node60.html\nnode27.html\nnode58.html\nnode1.html\nnode270.html\n---\n# 3.21 Standard Module user\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 exists).\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\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 module user's) global\nnamespace. Errors during this phase are not caught; that's up to the\nprogram that imports the user module, if it wishes. The home\ndirectory is assumed to be named by the HOME environment\nvariable; if this is not set, the current directory is used.\nThe user's `.pythonrc.py' could conceivably test for\nsys.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\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 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.\nSee Also:\nsite (site-wide customization mechanism)\n---\nnode60.html\nnode27.html\nnode58.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2343, "url": "https://docs.python.org/1.5/lib/node59.html"} {"title": "Boolean Operations", "text": "node7.html\nnode4.html\nnode5.html\nnode1.html\nnode270.html\n---\n## Boolean Operations\nThese are the Boolean operations, ordered by ascending priority:\nOperation | Result | Notes\n,\nNotes:\n---\nguido@python.org", "python_version": "1.5", "length": 204, "url": "https://docs.python.org/1.5/lib/node6.html"} {"title": "Built-in Module __builtin__", "text": "node61.html\nnode27.html\nnode59.html\nnode1.html\nnode270.html\n---\n# Built-in Module __builtin__\nThis module provides direct access to all `built-in' identifiers of\nPython; e.g. __builtin__.open is the full name for the built-in\nfunction open(). See section 2.3 (node26.html#builtinfuncs), ``Built-in\nFunctions.''\n---\nguido@python.org", "python_version": "1.5", "length": 331, "url": "https://docs.python.org/1.5/lib/node60.html"} {"title": "Built-in Module __main__", "text": "node62.html\nnode27.html\nnode60.html\nnode1.html\nnode270.html\n---\n# Built-in Module __main__\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.\n---\nguido@python.org", "python_version": "1.5", "length": 282, "url": "https://docs.python.org/1.5/lib/node61.html"} {"title": "4 String Services", "text": "node63.html\nlib.html\nnode61.html\nnode1.html\nnode270.html\n---\n# 4 String Services\nThe modules described in this chapter provide a wide range of string\nmanipulation operations. Here's an overview:\n---\n- 4.1 Standard Module string (node63.html#SECTION005100000000000000000)\n4.2 Built-in Module re (node64.html#SECTION005200000000000000000)\n- Regular Expression Syntax (node65.html#SECTION005210000000000000000)\nModule Contents (node66.html#SECTION005220000000000000000)\nRegular Expression Objects (node67.html#SECTION005230000000000000000)\nMatch Objects (node68.html#SECTION005240000000000000000)\n4.3 Built-in Module regex (node69.html#SECTION005300000000000000000)\n- Regular Expressions (node70.html#SECTION005310000000000000000)\nModule Contents (node71.html#SECTION005320000000000000000)\n4.4 Standard Module regsub (node72.html#SECTION005400000000000000000)\n4.5 Built-in Module struct (node73.html#SECTION005500000000000000000)\n4.6 Standard Module StringIO (node74.html#SECTION005600000000000000000)\n4.7 Built-in Module soundex (node75.html#SECTION005700000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1090, "url": "https://docs.python.org/1.5/lib/node62.html"} {"title": "4.1 Standard Module string", "text": "node64.html\nnode62.html\nnode62.html\nnode1.html\nnode270.html\n---\n# 4.1 Standard Module string\nThis module defines some constants useful for checking character\nclasses and some useful string functions. See the module\nre for string functions based on regular expressions.\nThe constants defined in this module are are:\nThe functions defined in this module are:\nThis module is implemented in Python. Much of its functionality has\nbeen reimplemented in the built-in module strop. However, you\nshould never import the latter module directly. When\nstring discovers that strop exists, it transparently\nreplaces parts of itself with the implementation from strop.\nAfter initialization, there is no overhead in using\nstring instead of strop.\n---\nnode64.html\nnode62.html\nnode62.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 811, "url": "https://docs.python.org/1.5/lib/node63.html"} {"title": "4.2 Built-in Module re", "text": "node65.html\nnode62.html\nnode63.html\nnode1.html\nnode270.html\n---\n# 4.2 Built-in Module re\nThis module provides regular expression matching operations similar to\nthose found in Perl. It's 8-bit clean: both patterns and strings may\ncontain null bytes and characters whose high bit is set. It is always\navailable.\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 two\ncharacter string containing a backslash and the letter 'n', while\n\"\\n\" is a one-character string containing a newline. Usually\npatterns will be expressed in Python code using this raw string notation.\n---\n- Regular Expression Syntax (node65.html#SECTION005210000000000000000)\nModule Contents (node66.html#SECTION005220000000000000000)\nRegular Expression Objects (node67.html#SECTION005230000000000000000)\nMatch Objects (node68.html#SECTION005240000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1459, "url": "https://docs.python.org/1.5/lib/node64.html"} {"title": "Regular Expression Syntax", "text": "node66.html\nnode64.html\nnode64.html\nnode1.html\nnode270.html\n---\n## 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.\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\ncharacters 'last'. (In the rest of this section, we'll write RE's in\nthis special font, 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 '$'.\n---\nnode66.html\nnode64.html\nnode64.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1864, "url": "https://docs.python.org/1.5/lib/node65.html"} {"title": "Module Contents", "text": "node67.html\nnode64.html\nnode65.html\nnode1.html\nnode270.html\n---\n## Module Contents\nThe module defines the following functions and constants, and an exception:\n---\nnode67.html\nnode64.html\nnode65.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 239, "url": "https://docs.python.org/1.5/lib/node66.html"} {"title": "Regular Expression Objects", "text": "node68.html\nnode64.html\nnode66.html\nnode1.html\nnode270.html\n---\n## Regular Expression Objects\nCompiled regular expression objects support the following methods and\nattributes:\n---\nnode68.html\nnode64.html\nnode66.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 256, "url": "https://docs.python.org/1.5/lib/node67.html"} {"title": "Match Objects", "text": "node69.html\nnode64.html\nnode67.html\nnode1.html\nnode270.html\n---\n## Match Objects\nMatchObject instances support the following methods and attributes:\nSee Also:\nJeffrey Friedl, Mastering Regular Expressions,\nO'Reilly. The Python material in this book dates from before the\nre module, but it covers writing good regular expression\npatterns in great detail.\n---\nnode69.html\nnode64.html\nnode67.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 434, "url": "https://docs.python.org/1.5/lib/node68.html"} {"title": "4.3 Built-in Module regex", "text": "node70.html\nnode62.html\nnode68.html\nnode1.html\nnode270.html\n---\n# 4.3 Built-in Module regex\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\nre module, which supports the more powerful\nand regular Perl-style regular expressions. Existing code should be\nconverted. The standard library module\nreconvert helps in converting\nregex style regular expressions to re\nstyle regular expressions. (For more conversion help, see the URL\nhttp://starship.skyport.net/crew/amk/regex/regex-to-re.html.)\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'\npattern 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{\n...}' headers from 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.\n---\n- Regular Expressions (node70.html#SECTION005310000000000000000)\nModule Contents (node71.html#SECTION005320000000000000000)\n---\nnode70.html\nnode62.html\nnode68.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2420, "url": "https://docs.python.org/1.5/lib/node69.html"} {"title": "Comparisons", "text": "node8.html\nnode4.html\nnode6.html\nnode1.html\nnode270.html\n---\n## 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, 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\nall when x < y is found to be false).\nThis table summarizes the comparison operations:\nOperation | Meaning | Notes\n,\nNotes:\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 (e.g., windows) support only a degenerate\nnotion of comparison where any two objects of that type are unequal.\nAgain, such objects are ordered arbitrarily but consistently.\n(Implementation note: objects of different types except numbers are\nordered by their type names; objects of the same types that don't\nsupport proper comparison are ordered by their address.)\nTwo more operations with the same syntactic priority, in and\nnot in, are supported only by sequence types (below).\n---\nnode8.html\nnode4.html\nnode6.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1291, "url": "https://docs.python.org/1.5/lib/node7.html"} {"title": "Regular Expressions", "text": "node71.html\nnode69.html\nnode69.html\nnode1.html\nnode270.html\n---\n## 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\nthis 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:\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---\nnode71.html\nnode69.html\nnode69.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1839, "url": "https://docs.python.org/1.5/lib/node70.html"} {"title": "Module Contents", "text": "node72.html\nnode69.html\nnode70.html\nnode1.html\nnode270.html\n---\n## Module Contents\nThe module defines these functions, and an exception:\n,\nCompiled regular expression objects support these methods:\n,\nCompiled regular expressions support these data attributes:\n---\nnode72.html\nnode69.html\nnode70.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 340, "url": "https://docs.python.org/1.5/lib/node71.html"} {"title": "4.4 Standard Module regsub", "text": "node73.html\nnode62.html\nnode71.html\nnode1.html\nnode270.html\n---\n# 4.4 Standard Module regsub\nThis module defines a number of functions useful for working with\nregular expressions (see built-in module regex).\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, 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 style regular\nexpressions to re style regular expressions. (For more\nconversion help, see the URL\nhttp://starship.skyport.net/crew/amk/regex/regex-to-re.html.)\n---\nnode73.html\nnode62.html\nnode71.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 884, "url": "https://docs.python.org/1.5/lib/node72.html"} {"title": "4.5 Built-in Module struct", "text": "node74.html\nnode62.html\nnode72.html\nnode1.html\nnode270.html\n---\n# 4.5 Built-in Module struct\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.\nSee also built-in module array.\nThe module defines the following exception and functions:\nFormat characters have the following meaning; the conversion between C\nand Python values should be obvious given their types:\nFormat | C | Python\nA format character may be preceded by an integral repeat count; e.g.\\\nthe format string '4h' means exactly the same as '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).\nFor the 'I' and 'L' format characters, the return\nvalue is a Python long 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:\nCharacter | Byte order | Size and alignment\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 sizeof\nexpression. This is always combined with native byte order.\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; int and\nlong are 4 bytes. Float and double are 32-bit and 64-bit IEEE floating\npoint numbers, respectively.\nNote the difference between '@' and '=': both use native\nbyte order, but the size and alignment of the latter is standardized.\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'>'.\nExamples (all using native byte order, size and alignment, on a\nbig-endian machine):\n```text\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>>>\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.\n(This only works when native size and alignment are in effect;\nstandard size and alignment does not enforce any alignment.)\n---\nnode74.html\nnode62.html\nnode72.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 3491, "url": "https://docs.python.org/1.5/lib/node73.html"} {"title": "4.6 Standard Module StringIO", "text": "node75.html\nnode62.html\nnode73.html\nnode1.html\nnode270.html\n---\n# 4.6 Standard Module StringIO\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.\nWhen a StringIO object is created, it can be initialized\nto an existing string by passing the string to the constructor.\nIf no string is given, the StringIO will start empty.\nThe method getvalue() can be called to retrieve the entire\ncontents of the ``file'' at any time before the StringIO\nobject's close() method is called. Calling close() will\nfree the memory buffer.\n---\nguido@python.org", "python_version": "1.5", "length": 658, "url": "https://docs.python.org/1.5/lib/node74.html"} {"title": "4.7 Built-in Module soundex", "text": "node76.html\nnode62.html\nnode74.html\nnode1.html\nnode270.html\n---\n# 4.7 Built-in Module soundex\nThe soundex algorithm takes an English word, and returns an\neasily-computed hash of it; this hash is intended to be the same for\nwords that sound alike. This module provides an interface to the\nsoundex algorithm.\nNote that the soundex algorithm is quite simple-minded, and isn't\nperfect by any measure. Its main purpose is to help looking up names\nin databases, when the name may be misspelled -- soundex hashes common\nmisspellings together.\n---\nguido@python.org", "python_version": "1.5", "length": 556, "url": "https://docs.python.org/1.5/lib/node75.html"} {"title": "5 Miscellaneous Services", "text": "node77.html\nlib.html\nnode75.html\nnode1.html\nnode270.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:\n---\n- 5.1 Built-in Module math (node77.html#SECTION006100000000000000000)\n5.2 Built-in Module cmath (node78.html#SECTION006200000000000000000)\n5.3 Standard Module whrandom (node79.html#SECTION006300000000000000000)\n5.4 Standard Module random (node80.html#SECTION006400000000000000000)\n5.5 Standard Module rand (node81.html#SECTION006500000000000000000)\n5.6 Built-in Module array (node82.html#SECTION006600000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 662, "url": "https://docs.python.org/1.5/lib/node76.html"} {"title": "5.1 Built-in Module math", "text": "node78.html\nnode76.html\nnode76.html\nnode1.html\nnode270.html\n---\n# 5.1 Built-in Module math\nThis module is always available.\nIt provides access to the mathematical functions defined by the C\nstandard.\nThey are:\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:\nSee Also:\ncmath (Complex number versions of many of these functions.)\n---\nnode78.html\nnode76.html\nnode76.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 675, "url": "https://docs.python.org/1.5/lib/node77.html"} {"title": "5.2 Built-in Module cmath", "text": "node79.html\nnode76.html\nnode77.html\nnode1.html\nnode270.html\n---\n# 5.2 Built-in Module cmath\nThis module is always available.\nIt provides access to mathematical functions for complex numbers.\nThe functions are:\nThe module also defines two mathematical constants:\nNote that the selection of functions is similar, but not identical, to\nthat in module math. The reason for having\ntwo modules is, that some users aren't interested in complex numbers,\nand perhaps don't even know what they are. They would rather have\nmath.sqrt(-1) raise an exception than return a complex number.\nAlso note that the functions defined in cmath always return a\ncomplex number, even if the answer can be expressed as a real number\n(in which case the complex number has an imaginary part of zero).\n---\nnode79.html\nnode76.html\nnode77.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 852, "url": "https://docs.python.org/1.5/lib/node78.html"} {"title": "5.3 Standard Module whrandom", "text": "node80.html\nnode76.html\nnode78.html\nnode1.html\nnode270.html\n---\n# 5.3 Standard Module whrandom\nThis module implements a Wichmann-Hill pseudo-random number generator\nclass that is also named whrandom. Instances of the\nwhrandom class have the following methods:\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\nN = whrandom.random() or:\n```text\ngenerator = whrandom.whrandom()\nN = generator.random()\n```\nSee Also:\nrandom (generators for various random distributions)\nWichmann, B. A. & Hill, I. D., ``Algorithm AS 183:\nAn efficient and portable pseudo-random number generator'',\nApplied Statistics 31 (1982) 188-190\n---\nguido@python.org", "python_version": "1.5", "length": 768, "url": "https://docs.python.org/1.5/lib/node79.html"} {"title": "Numeric Types", "text": "node9.html\nnode4.html\nnode7.html\nnode1.html\nnode270.html\n---\n## 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 `L'\nor `l' suffix yield long integers\n(`L' is preferred because `1l' looks too much like eleven!).\nNumeric literals containing a decimal point or an exponent sign yield\nfloating point numbers. Appending `j' or `J' to a numeric\nliteral 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.footnode.html#965\nThe 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):\nOperation | Result | Notes\n,\nNotes:\n---\n- Bit-string Operations on Integer Types (node9.html#SECTION003141000000000000000)\n---\nnode9.html\nnode4.html\nnode7.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2010, "url": "https://docs.python.org/1.5/lib/node8.html"} {"title": "5.4 Standard Module random", "text": "node81.html\nnode76.html\nnode79.html\nnode1.html\nnode270.html\n---\n# 5.4 Standard Module random\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 module exports the following functions, which are exactly\nequivalent to those in the whrandom module: choice,\nrandint, random, uniform. See the documentation\nfor the whrandom module for these functions.\nThe following functions specific to the random module are also\ndefined, and all return real values. Function parameters are named\nafter the corresponding variables in the distribution's equation, as\nused in common mathematical practice; most of these equations can be\nfound in any statistics text.\nSee Also:\nwhrandom (the standard Python random number generator)\n---\nnode81.html\nnode76.html\nnode79.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1061, "url": "https://docs.python.org/1.5/lib/node80.html"} {"title": "5.5 Standard Module rand", "text": "node82.html\nnode76.html\nnode80.html\nnode1.html\nnode270.html\n---\n# 5.5 Standard Module rand\nThe rand module simulates the C library's rand()\ninterface, though the results aren't necessarily compatible with any\ngiven library's implementation. While still supported for\ncompatibility, the rand module is now considered obsolete; if\npossible, use the whrandom module instead.\nSee Also:\nwhrandom (the standard Python random number generator)\n---\nguido@python.org", "python_version": "1.5", "length": 457, "url": "https://docs.python.org/1.5/lib/node81.html"} {"title": "5.6 Built-in Module array", "text": "node83.html\nnode76.html\nnode81.html\nnode1.html\nnode270.html\n---\n# 5.6 Built-in Module array\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 like lists,\nexcept that the type of objects stored in them is constrained. The\ntype is specified at object creation time by using a type code,\nwhich is a single character. The following type codes are defined:\nTypecode | Type | Minimal size in bytes\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 can't represent the full range of C's unsigned (long) integers.\nSee also built-in module struct.\nThe module defines the following function:\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(``). Examples:\n```text\narray('l')\narray('c', 'hello world')\narray('l', [1, 2, 3, 4, 5])\narray('d', [1.0, 2.0, 3.14])\n```\n---\nnode83.html\nnode76.html\nnode81.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1619, "url": "https://docs.python.org/1.5/lib/node82.html"} {"title": "6 Generic Operating System Services", "text": "node84.html\nlib.html\nnode82.html\nnode1.html\nnode270.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 other\nsystems as well. Here's an overview:\n---\n- 6.1 Standard Module os (node84.html#SECTION007100000000000000000)\n6.2 Built-in Module time (node85.html#SECTION007200000000000000000)\n6.3 Standard Module getopt (node86.html#SECTION007300000000000000000)\n6.4 Standard Module tempfile (node87.html#SECTION007400000000000000000)\n6.5 Standard Module errno (node88.html#SECTION007500000000000000000)\n6.6 Standard Module glob (node89.html#SECTION007600000000000000000)\n6.7 Standard Module fnmatch (node90.html#SECTION007700000000000000000)\n6.8 Standard Module locale (node91.html#SECTION007800000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 989, "url": "https://docs.python.org/1.5/lib/node83.html"} {"title": "6.1 Standard Module os", "text": "node85.html\nnode83.html\nnode83.html\nnode1.html\nnode270.html\n---\n# 6.1 Standard Module os\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.\nWhen the optional built-in module posix is available, this\nmodule exports the same functions and data as posix; otherwise,\nit searches for an OS dependent built-in module like mac and\nexports the same functions and data as found there. The design of all\nPython's built-in OS dependent modules is such that as long as the same\nfunctionality is available, it uses the same interface; e.g., the\nfunction os.stat(file) returns stat info about a file in a\nformat compatible with the POSIX interface.\nExtensions peculiar to a particular OS are also available through the\nos module, but using them is of course a threat to portability!\nNote that after the first time os is imported, there is no\nperformance penalty in using functions from os instead of\ndirectly from the OS dependent built-in module, so there should be\nno reason not to use os!\nIn addition to whatever the correct OS dependent module exports, the\nfollowing variables and functions are always exported by os:\n(The functions os.execv() and execve() are not\ndocumented here, since they are implemented by the OS dependent\nmodule. If the OS dependent module doesn't define either of these,\nthe functions that rely on it will raise an exception. They are\ndocumented in the section on module posix, together with all\nother functions that os imports from the OS dependent module.)\n---\nnode85.html\nnode83.html\nnode83.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1658, "url": "https://docs.python.org/1.5/lib/node84.html"} {"title": "6.2 Built-in Module time", "text": "node86.html\nnode83.html\nnode84.html\nnode1.html\nnode270.html\n---\n# 6.2 Built-in Module time\nThis module provides various time-related functions.\nIt is always available.\nAn explanation of some terminology and conventions is in order.\n- The ``epoch'' is the point where the time starts. On January 1st of that\nyear, at 0 hours, the ``time since the epoch'' is zero. For Unix, the\nepoch is 1970. To find out what the epoch is, look at gmtime(0).UTC is Coordinated Universal Time (formerly known as Greenwich Mean\nTime). The acronym UTC is not a mistake but a compromise between\nEnglish and French.DST is Daylight Saving Time, an adjustment of the timezone by\n(usually) one hour during part of the year. DST rules are magic\n(determined by local law) and can change from year to year. The C\nlibrary has a table containing the local rules (often it is read from\na system file for flexibility) and is the only source of True Wisdom\nin this respect.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.On the other hand, the precision of time() and sleep()\nis better than their Unix equivalents: times are expressed as floating\npoint numbers, time() returns the most accurate time available\n(using Unix gettimeofday() where available), and sleep()\nwill accept a time with a nonzero fraction (Unix select() is\nused to implement this, where available).The time tuple as returned by gmtime() and localtime(),\nor as accpted by mktime() is a tuple of 9\nintegers: year (e.g. 1993), month (1-12), day (1-31), hour\n(0-23), minute (0-59), second (0-59), weekday (0-6, monday is 0),\nJulian day (1-366) and daylight savings flag (-1, 0 or 1).\nNote that unlike the C structure, the month value is a range of 1-12, not\n0-11. A year value less than 100 will typically be silently converted to\n1900 plus the year value. A -1 argument as daylight savings flag, passed to\nmktime() will usually result in the correct daylight savings\nstate to be filled in.\nThe module defines the following functions and data items:\n---\nnode86.html\nnode83.html\nnode84.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2287, "url": "https://docs.python.org/1.5/lib/node85.html"} {"title": "6.3 Standard Module getopt", "text": "node87.html\nnode83.html\nnode85.html\nnode1.html\nnode270.html\n---\n# 6.3 Standard Module getopt\nThis module helps scripts to parse the command line arguments in\nsys.argv.\nIt supports the same conventions as the Unix\ngetopt()\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.\nIt defines the function\ngetopt.getopt(args, options [, long_options])\nand the exception\ngetopt.error.\nThe first argument to\ngetopt()\nis the argument list passed to the script with its first element\nchopped off (i.e.,\nsys.argv[1:]).\nThe second argument is the string of option letters that the\nscript wants to recognize, with options that require an argument\nfollowed by a colon (i.e., the same format that Unix\ngetopt()\nuses).\nThe third option, if specified, is a list of strings with the names of\nthe long options which should be supported. The leading '--'\ncharacters should not be included in the option name. Options which\nrequire an argument should be followed by an equal sign ('=').\nThe return value consists of two elements: the first is a list of\noption-and-value pairs; the second is the list of program arguments\nleft after the option list was stripped (this is a trailing slice of the\nfirst argument).\nEach option-and-value pair returned has the option as its first element,\nprefixed with a hyphen (e.g.,\n'-x'),\nand the option argument as its second element, or an empty string if the\noption has no argument.\nThe options occur in the list in the same order in which they were\nfound, thus allowing multiple occurrences. Long and short options may\nbe mixed.\nAn example using only Unix style options:\n```text\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:\n```text\n>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'\n>>> args = string.split(s)\n>>> args\n['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']\n>>> optlist, args = getopt.getopt(args, 'x', [\n... 'condition=', 'output-file=', 'testing'])\n>>> optlist\n[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]\n>>> args\n['a1', 'a2']\n>>>\n```\nThe exception\ngetopt.error\nis raised when an unrecognized option is found in the argument list or\nwhen an option requiring an argument is given none.\nThe argument to the exception is a string indicating the cause of the\nerror. For long options, an argument given to an option which does\nnot require one will also cause this exception to be raised.\n---\nnode87.html\nnode83.html\nnode85.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2890, "url": "https://docs.python.org/1.5/lib/node86.html"} {"title": "6.4 Standard Module tempfile", "text": "node88.html\nnode83.html\nnode86.html\nnode1.html\nnode270.html\n---\n# 6.4 Standard Module tempfile\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().\nWarning: if a Unix process uses mktemp(), then calls\nfork() and both parent and child continue to use\nmktemp(), the processes will generate conflicting temporary\nnames. To resolve this, the child process should assign None\nto template, to force recomputing the default on the next call\nto mktemp().\n---\nnode88.html\nnode83.html\nnode86.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 960, "url": "https://docs.python.org/1.5/lib/node87.html"} {"title": "6.5 Standard Module errno", "text": "node89.html\nnode83.html\nnode87.html\nnode1.html\nnode270.html\n---\n# 6.5 Standard Module errno\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. Of the following list, symbols\nthat are not used on the current platform are not defined by the\nmodule.\nThe module also defines the dictionary variable errorcode which\nmaps numeric error codes back to their symbol names, so that e.g.\nerrno.errorcode[errno.EPERM] == 'EPERM'. To translate a\nnumeric error code to an error message, use os.strerror().\nSymbols available can include:\n---\nnode89.html\nnode83.html\nnode87.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 780, "url": "https://docs.python.org/1.5/lib/node88.html"} {"title": "6.6 Standard Module glob", "text": "node90.html\nnode83.html\nnode88.html\nnode1.html\nnode270.html\n---\n# 6.6 Standard Module glob\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:\n`1.gif', `2.txt', and `card.gif'. glob.glob()\nwill produce the following results. Notice how any leading components\nof the path are preserved.\n```text\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```\n---\nguido@python.org", "python_version": "1.5", "length": 918, "url": "https://docs.python.org/1.5/lib/node89.html"} {"title": "Bit-string Operations on Integer Types", "text": "node10.html\nnode8.html\nnode8.html\nnode1.html\nnode270.html\n---\n### 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):\nOperation | Result | Notes\n,\nNotes:\n---\nguido@python.org", "python_version": "1.5", "length": 781, "url": "https://docs.python.org/1.5/lib/node9.html"} {"title": "6.7 Standard Module fnmatch", "text": "node91.html\nnode83.html\nnode89.html\nnode1.html\nnode270.html\n---\n# 6.7 Standard Module fnmatch\nThis module provides support for Unix shell-style wildcards, which\nare not the same as regular expressions (which are documented\nin the re module). The special characters\nused in shell-style wildcards are:\nNote that the filename separator ('/' on Unix) is not\nspecial to this module. See module glob\nfor pathname expansion (glob uses fnmatch() to\nmatch filename segments).\nSee Also:\nglob (Shell-style path expansion)\n---\nguido@python.org", "python_version": "1.5", "length": 531, "url": "https://docs.python.org/1.5/lib/node90.html"} {"title": "6.8 Standard Module locale", "text": "node92.html\nnode83.html\nnode90.html\nnode1.html\nnode270.html\n---\n# 6.8 Standard Module locale\nThe locale module opens access to the POSIX locale database\nand functionality. The POSIX locale mechanism allows applications\nto integrate certain cultural aspects into an applications, 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 _locale\nmodule, which in turn uses an ANSI C locale implementation if\navailable.\nThe locale module defines the following functions:\nExample:\n```text\n>>> import locale\n>>> locale.open(locale.LC_ALL,\"de\") #setting locale to German\n>>> locale.strcoll(\"f\\344n\",\"foo\") #comparing a string containing an umlaut\n>>> can.close()\n```\n---\nnode92.html\nnode83.html\nnode90.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 838, "url": "https://docs.python.org/1.5/lib/node91.html"} {"title": "7 Optional Operating System Services", "text": "node93.html\nlib.html\nnode91.html\nnode1.html\nnode270.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:\n---\n- 7.1 Built-in Module signal (node93.html#SECTION008100000000000000000)\n7.2 Built-in Module socket (node94.html#SECTION008200000000000000000)\n- Socket Objects (node95.html#SECTION008210000000000000000)\nExample (node96.html#SECTION008220000000000000000)\n7.3 Built-in Module select (node97.html#SECTION008300000000000000000)\n7.4 Built-in Module thread (node98.html#SECTION008400000000000000000)\n7.5 Standard Module Queue (node99.html#SECTION008500000000000000000)\n- Queue Objects (node100.html#SECTION008510000000000000000)\n7.6 Standard Modules anydbm and dumbdbm (node101.html#SECTION008600000000000000000)\n7.7 Standard Module whichdb (node102.html#SECTION008700000000000000000)\n7.8 Built-in Module zlib (node103.html#SECTION008800000000000000000)\n7.9 Built-in Module gzip (node104.html#SECTION008900000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1245, "url": "https://docs.python.org/1.5/lib/node92.html"} {"title": "7.1 Built-in Module signal", "text": "node94.html\nnode92.html\nnode92.html\nnode1.html\nnode270.html\n---\n# 7.1 Built-in Module signal\nThis module provides mechanisms to use signal handlers in Python.\nSome general rules for working with signals 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.There is no way to ``block'' signals temporarily from critical\nsections (since this is not supported by all Unix flavors).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.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.Because the C signal handler always returns, it makes little sense to\ncatch synchronous errors like SIGFPE or SIGSEGV.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), SIGINT is translated\ninto a KeyboardInterrupt exception, and SIGTERM is\ncaught so that necessary cleanup (especially sys.exitfunc) can\nbe performed before actually terminating. All of these can be\noverridden.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:\n---\nnode94.html\nnode92.html\nnode92.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2528, "url": "https://docs.python.org/1.5/lib/node93.html"} {"title": "7.2 Built-in Module socket", "text": "node95.html\nnode92.html\nnode93.html\nnode1.html\nnode270.html\n---\n# 7.2 Built-in Module socket\nThis module provides access to the BSD socket interface.\nIt is available on Unix systems that support this interface.\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 Interprocess\nCommunication Tutorial, by Samuel J. Leffler et al, both in the\nUnix Programmer's Manual, Supplementary Documents 1 (sections PS1:7\nand PS1:8). The Unix manual pages for the various socket-related\nsystem calls are also a valuable source of information on the details of\nsocket semantics.\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 various socket system\ncalls. Parameter types are somewhat higher-level than in the C\ninterface: as with read() and write() operations on Python\nfiles, buffer allocation on receive operations is automatic, and\nbuffer length is implicit on send operations.\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 family,\nwhere 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 socket.error.\nNon-blocking mode is supported through the setblocking()\nmethod.\nThe module socket exports the following constants and functions:\n---\n- Socket Objects (node95.html#SECTION008210000000000000000)\nExample (node96.html#SECTION008220000000000000000)\n---\nnode95.html\nnode92.html\nnode93.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 2397, "url": "https://docs.python.org/1.5/lib/node94.html"} {"title": "Socket Objects", "text": "node96.html\nnode94.html\nnode94.html\nnode1.html\nnode270.html\n---\n## Socket Objects\n,\nSocket objects have the following methods. Except for\nmakefile() these correspond to Unix system calls applicable to\nsockets.\nNote that there are no methods read() or write(); use\nrecv() and send() without flags argument instead.\n---\nnode96.html\nnode94.html\nnode94.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 394, "url": "https://docs.python.org/1.5/lib/node95.html"} {"title": "Example", "text": "node97.html\nnode94.html\nnode95.html\nnode1.html\nnode270.html\n---\n## 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, accept\n(possibly repeating the accept to service more than one client),\nwhile a client only needs the sequence socket, connect.\nAlso note that the server does not send/receive on the\nsocket it is listening on but on the new socket returned by\naccept.\n```text\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# 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```\nSee Also:\nSocketServer (classes that simplify writing network servers)\n---\nguido@python.org", "python_version": "1.5", "length": 1279, "url": "https://docs.python.org/1.5/lib/node96.html"} {"title": "7.3 Built-in Module select", "text": "node98.html\nnode92.html\nnode96.html\nnode1.html\nnode270.html\n---\n# 7.3 Built-in Module select\nThis module provides access to the function select available in\nmost Unix versions. It defines the following:\n---\nguido@python.org", "python_version": "1.5", "length": 223, "url": "https://docs.python.org/1.5/lib/node97.html"} {"title": "7.4 Built-in Module thread", "text": "node99.html\nnode92.html\nnode97.html\nnode1.html\nnode270.html\n---\n# 7.4 Built-in Module thread\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:\n- Threads interact strangely with interrupts: the\nKeyboardInterrupt exception will be received by an arbitrary\nthread. (When the signal module is\navailable, interrupts always go to the main thread.)Calling sys.exit() or raising the SystemExit exception is\nequivalent to calling thread.exit_thread().Not all built-in functions that may block waiting for I/O allow other\nthreads to run. (The most popular ones (sleep(), read(),\nselect()) work as expected.)It is not possible to interrupt the acquire() method on a lock\n- the KeyboardInterrupt exception will happen after the lock\nhas been acquired.When the main thread exits, it is system defined whether the other\nthreads survive. On SGI IRIX using the native thread implementation,\nthey survive. On most other systems, they are killed without\nexecuting ``try-finally'' clauses or executing object destructors.\nWhen the main thread exits, it doesn't do any of its usual cleanup\n(except that ``try-finally'' clauses are honored), and the standard\nI/O files are not flushed.\n---\nnode99.html\nnode92.html\nnode97.html\nnode1.html\nnode270.html\nguido@python.org", "python_version": "1.5", "length": 1731, "url": "https://docs.python.org/1.5/lib/node98.html"} {"title": "7.5 Standard Module Queue", "text": "node100.html\nnode92.html\nnode98.html\nnode1.html\nnode270.html\n---\n# 7.5 Standard Module Queue\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 exception:\n---\n- Queue Objects (node100.html#SECTION008510000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 553, "url": "https://docs.python.org/1.5/lib/node99.html"} {"title": "Python 1.5 Reference Manual", "text": "[Next] (ref-2.html)[Contents] (ref-2.html)[Index]\n# Python Reference Manual\n---\nGuido van Rossum\nCorporation for National Research Initiatives (CNRI)\n1895 Preston White Drive, Reston, Va 20191, USA\nE-mail: `guido@cnri.reston.va.us`, `guido@python.org`\nDecember 31, 1997\nRelease 1.5\nAbstract\nPython is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for rapid application development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.\nThis reference manual describes the syntax and \"core semantics\" of the language. It is terse, but attempts to be exact and complete. The semantics of non-essential built-in object types and of the built-in functions and modules are described in the Python Library Reference. For an informal introduction to the language, see the Python Tutorial. For C or C++ programmers, two additional manuals exist: Extending and Embedding the Python Interpreter describes the high-level picture of how to write a Python extension module, and the Python/C API Reference Manual describes the interfaces available to C/C++ programmers in detail.\nCopyright © 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands.\nAll Rights Reserved\nPermission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI or Corporation for National Research Initiatives or CNRI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission.\nWhile CWI is the initial source for this software, a modified version is made available by the Corporation for National Research Initiatives (CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-2.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 3141, "url": "https://docs.python.org/1.5/ref/ref-1.html"} {"title": "Chapter 8: Top-level components", "text": "[Next] [Previous] (ref-9.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 8: Top-level components\n---\nThe Python interpreter can get its input from a number of sources: from a script passed to it as standard input or as program argument, typed in interactively, from a module source file, etc. This chapter gives the syntax used in these cases.\n## 8.1 Complete Python programs\nWhile a language specification need not prescribe how the language interpreter is invoked, it is useful to have a notion of a complete Python program. A complete Python program is executed in a minimally initialized environment: all built-in and standard modules are available, but none have been initialized, except for sys (various system services), __builtin__ (built-in functions, exceptions and None) and __main__. The latter is used to provide the local and global name space for execution of the complete program.\nThe syntax for a complete Python program is that for file input, described in the next section.\nThe interpreter may also be invoked in interactive mode; in this case, it does not read and execute a complete program but reads and executes one statement (possibly compound) at a time. The initial environment is identical to that of a complete program; each statement is executed in the name space of __main__.\nUnder UNIX , a complete program can be passed to the interpreter in three forms: with the -c string command line option, as a file passed as the first command line argument, or as standard input. If the file or standard input is a tty device, the interpreter enters interactive mode; otherwise, it executes the file as a complete program.\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);\nwhen parsing a module;\nwhen parsing a string passed to the exec statement;\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 line in interactive mode; this is needed to help the parser detect the end of the input.\n## 8.4 Expression input\nThere are two forms of expression input. Both ignore leading whitespace. The 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 built-in function raw_input() or the readline() method of file objects.\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] [Previous] (ref-9.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 11668, "url": "https://docs.python.org/1.5/ref/ref-10.html"} {"title": "ref-2", "text": "[Next] (ref-3.html)[Previous] (ref-1.html)[Top] (ref-1.html)[Index]\nPython 1.5 Reference Manual\n---\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nFM pgf ignored\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-3.html)[Previous] (ref-1.html)[Top] (ref-1.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 1607, "url": "https://docs.python.org/1.5/ref/ref-2.html"} {"title": "Chapter 1: Introduction", "text": "[Next] (ref-4.html)[Previous] (ref-2.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 1: Introduction\n---\nThis reference manual describes the Python programming language. It is not intended as a tutorial.\nWhile I am trying to be as precise as possible, I have chosen to use English rather than formal specifications for everything except syntax and lexical analysis. This should make the document more understandable to the average reader, but will leave room for ambiguities. Consequently, if you were coming from Mars and tried to re-implement Python from this document alone, you might have to guess things and in fact you would probably end up implementing quite a different language. On the other hand, if you are using Python and wonder what the precise rules about a particular area of the language are, you should definitely be able to find them here. If you would like to see a more formal definitition of the language, maybe you could volunteer your time -- or invent a cloning machine :-).\nIt is dangerous to add too many implementation details to a language reference document -- the implementation may change, and other implementations of the same language may work differently. On the other hand, there is currently only one Python implementation in widespread use, and its particular quirks are sometimes worth being mentioned, especially where the implementation imposes additional limitations. Therefore, you'll find short \"implementation notes\" sprinkled throughout the text.\nEvery Python implementation comes with a number of built-in and standard modules. These are not documented here, but in the separate Python Library Reference document. A few built-in modules are mentioned when they interact in a significant way with the language definition.\n## 1.1 Notation\nThe descriptions of lexical analysis and syntax use a modified BNF grammar 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 a sequence of zero or more lc_letters and underscores. An lc_letter in turn is any of the single characters 'a' through 'z'. (This rule is actually adhered to for the names used in lexical and grammar rules in this document.)\nEach rule begins with a name (which is the name defined by the rule) and a colon. A vertical bar (|) is used to separate alternatives; it is the least binding operator in this notation. A star (*) means zero or more repetitions of the preceding item; likewise, a plus (+) means one or more repetitions, and a phrase enclosed in square brackets ([ ]) means zero or one occurrences (in other words, the enclosed phrase is optional). The * and + operators bind as tightly as possible; parentheses are used for grouping. Literal strings are enclosed in quotes. White space is only meaningful to separate tokens. Rules are normally contained on a single line; rules with many alternatives may be formatted alternatively with each line after the first beginning with a vertical bar.\nIn lexical definitions (as in the example above), two more conventions are used: Two literal characters separated by three dots mean a choice of any single character in the given (inclusive) range of ASCII characters. A phrase between angular brackets (<...>) gives an informal description of the symbol defined; e.g. this could be used to describe the notion of 'control character' if needed.\nEven though the notation used is almost the same, there is a big difference between the meaning of lexical and syntactic definitions: a lexical definition operates on the individual characters of the input source, while a syntax definition operates on the stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter (\"Lexical Analysis\") are lexical definitions; uses in subsequent chapters are syntactic definitions.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-4.html)[Previous] (ref-2.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 4139, "url": "https://docs.python.org/1.5/ref/ref-3.html"} {"title": "Chapter 2: Lexical analysis", "text": "[Next] (ref-5.html)[Previous] (ref-3.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 2: Lexical analysis\n---\nA Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens.\nPython uses the 7-bit ASCII character set for program text and string literals. 8-bit characters may be used in string literals and comments but their interpretation is platform dependent; the proper way to insert 8-bit characters in string literals is by using octal or hexadecimal escape sequences.\nThe run-time character set depends on the I/O devices connected to the program but is generally a superset of ASCII.\nFuture compatibility note: It may be tempting to assume that the character set for 8-bit characters is ISO Latin-1 (an ASCII superset that covers most western languages that use the Latin alphabet), but it is possible that in the future Unicode text editors will become common. These generally use the UTF-8 encoding, which is also an ASCII superset, but with very different use for the characters with ordinals 128-255. While there is no consensus on this subject yet, it is unwise to assume either Latin-1 or UTF-8, even though the current implementation appears to favor Latin-1. This applies both to the source character set and the run-time character set.\n## 2.1 Line structure\nA Python program is divided in a number of logical lines.\n### 2.1.1 Logical lines\nThe end of each logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g. between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.\n### 2.1.2 Physical lines\nA physical line ends in whatever the current platform's convention is for terminating lines. On UNIX, this is the ASCII LF (linefeed) character. On DOS/Windows, it is the ASCII sequence CR LF (return followed by linefeed). On Macintosh, it is the ASCII CR (return) character.\n### 2.1.3 Comments\nA comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax; they are not tokens.\n### 2.1.4 Explicit line joining\nTwo or more physical lines may be joined into logical lines using backslash characters (\\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash 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 not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.\n### 2.1.5 Implicit line joining\nExpressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For 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 continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicit continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.\n### 2.1.6 Blank lines\nA logical line that contains only spaces, tabs, formfeeds, and possibly a comment, is ignored (i.e., no NEWLINE token is generated), except that during interactive input of statements, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.\n### 2.1.7 Indentation\nLeading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.\nFirst, tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to there is a multiple of eight (this is intended to be the same rule as used by UNIX). The total number of spaces preceding the first non-blank character then determines the line's indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.\nCross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file.\nA formfeed character may be present at the start of the line; formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).\nThe indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.\nBefore the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line's indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.\nHere is an example of a correctly (though confusingly) indented piece of 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 last error is found by the lexical analyzer -- the indentation of return r does not match a level popped off the stack.)\n### 2.1.8 Whitespace between tokens\nExcept at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., `ab` is one token, but `a` `b` is two tokens).\n## 2.2 Other tokens\nBesides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token when read from left to right.\n## 2.3 Identifiers and keywords\nIdentifiers (also referred to as names) are described by the following lexical 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.\n### 2.3.1 Keywords\nThe following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. 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```\n### 2.3.2 Reserved classes of identifiers\nCertain classes of identifiers (besides keywords) have special meanings. These are:\n(XXX need section references here.)\n## 2.4 Literals\nLiterals are notations for constant values of some built-in types\n### 2.4.1 String literals\nString literals are described by the following lexical definitions:\n```text\n\nstringliteral: [rawprefix] (shortstring | longstring)\nrawprefix: \"r\" | \"R\"\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 single quotes (') or double quotes (\"). They can also be enclosed in groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for backslash escape sequences.\nIn \"long strings\" (strings surrounded by sets of three quotes), unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A \"quote\" is the character used to open the string, i.e. either ' or \".)\nUnless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:\nIn strict compatibility with Standard C, up to three octal digits are accepted, but an unlimited number of hex digits is taken to be part of the hex escape (and then the lower 8 bits of the resulting hex number are used in all current implementations...).\nUnlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.)\nWhen an 'r' or 'R' prefix is present, all backslashes are left in the string. For example, the string literal `r\"\\n\"` consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, `r\"\\\"\"` is a valid string literal consisting of two characters: a backslash and a double quote.\n#### 2.4.1.1 String literal concatenation\nMultiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, `\"hello\"` `'world'` is equivalent to `\"helloworld\"`. This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:\n```text\n\nregex.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 implemented at compile time. The '+' operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component.\n### 2.4.2 Numeric literals\nThere are four types of numeric literals: plain integers, long integers, floating point numbers, and imaginary numbers.\n#### 2.4.2.1 Integer and long integer literals\nInteger and long integer literals are described by the following lexical 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 for long integers, it is strongly recommended to always use 'L', since the letter 'l' looks too much like the digit '1'.\nPlain integer decimal literals must be at most 2147483647 (i.e., the largest positive integer, using 32-bit arithmetic). Plain octal and hexadecimal literals may be as large as 4294967295, but values larger than 2147483647 are converted to a negative value by subtracting 4294967296. There is no limit for long integer literals apart from what 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```\n#### 2.4.2.2 Floating point literals\nFloating point literals are described by the following lexical definitions:\n```text\n\nfloatnumber: pointfloat | exponentfloat\npointfloat: [intpart] fraction | intpart \".\"\nexponentfloat: (intpart | 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 an octal integer. The allowed range of floating point literals is implementation-dependent. Some examples of floating point literals:\n```text\n\n3.14 10. .001 1e100 3.14e-10\n```\n#### 2.4.2.3 Imaginary literals\nImaginary literals are described by the following lexical definitions:\n```text\n\nimagnumber: (floatnumber | intpart) (\"j\"|\"J\")\n```\nAn imaginary literals yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g. `(3+4j).` Some examples of imaginary literals:\n```text\n\n3.14j 10.j 10 j .001j 1e100j 3.14e-10j\n```\nNote that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator '-' and the literal 1.\n## 2.5 Operators\nThe following tokens are operators:\n```text\n\n+ - * ** / %\n<< >> & | ^ ~\n< > <= >= == != <>\n```\nThe comparison operators <> and != are alternate spellings of the same operator; != is the preferred spelling, <> is obsolescent.\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 sequence of three periods has a special meaning as ellipses in slices.\nThe following printing ASCII characters have special meaning as part of 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 occurrence outside string literals and comments is an unconditional error:\n```text\n\n@ $ ?\n```\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-5.html)[Previous] (ref-3.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 15626, "url": "https://docs.python.org/1.5/ref/ref-4.html"} {"title": "Chapter 3: Data model", "text": "[Next] (ref-6.html)[Previous] (ref-4.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 3: Data model\n---\n## 3.1 Objects, values and types\nObjects are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In conformance to Von Neumann's model of a \"stored program computer\", code is also represented by objects.)\nEvery object has an identity, a type and a value. An object's identity never changes once it has been created; you may think of it as the object's address in memory. The '`is`' operator compares the identity of two objects; the '`id()`' function returns an integer representing its identity (currently implemented as its address). An object's type is also unchangeable. It determines the operations that an object supports (e.g. \"does it have a length?\") and also defines the possible values for objects of that type. The '`type()`' function returns an object's type (which is an object itself). The value of some objects can change. The '`==`' operator compares the value of two objects. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. An object's (im)mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.\nObjects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether -- it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable. (Implementation note: the current implementation uses a reference-counting scheme which collects most objects as soon as they become unreachable, but never collects garbage containing circular references.)\nNote that the use of the implementation's tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a '`try...except`' statement may keep objects alive.\nSome objects contain references to \"external\" resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to always explicitly close such objects. The '`try... finally`' statement provides a convenient way to do this.\nSome objects contain references to other objects; these are called containers. Examples of containers are tuples, lists and dictionaries. The references are part of a container's value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the (im)mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.\nTypes affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g. after ''`a = 1; b =`1'', a and b may or may not refer to the same object with the value one, depending on the implementation, but after ''`c = []; d = []`'', c and d are guaranteed to refer to two different, unique, newly created empty lists. (Note that ''`c = d = []`'' assigns the same object to both `c` and `d`.)\n## 3.2 The standard type hierarchy\nBelow is a list of the types that are built into Python. Extension modules written in C can define additional types. Future versions of Python may add types to the type hierarchy (e.g. rational numbers, efficiently stored arrays of integers, etc.).\nSome of the type descriptions below contain a paragraph listing 'special attributes'. These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future. There are also some 'generic' special attributes, not listed with the individual objects: __methods__ is a list of the method names of a built-in object, if it has any; __members__ is a list of the data attribute names of a built-in object, if it has any.\nNone This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g. it is returned from functions that don't explicitly return anything. Its truth value is false.\nEllipsis This type has a single value. There is a single object with this value. This object is accessed through the built-in name Ellipsis. It is used to indicate the presence of the ''...'' syntax in a slice. Its truth value is true.\nNumbers These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject 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. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation falls outside this range, the exception OverflowError is raised. For the purpose of shift and mask operations, integers are assumed to have a binary, 2's complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).\nLong integers These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2's complement which gives the illusion of an infinite string of sign bits extending to the left.\nThe rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. For any operation except left shift, if it yields a result in the plain integer domain without causing overflow, it will yield the same result in the long integer domain or when using mixed operands.\nFloating point numbers These represent machine-level double precision floating point numbers. You are at the mercy of the underlying machine architecture and C implementation for the accepted range and handling of overflow. Python does not support single-precision floating point numbers; the savings in CPU and memory usage that are usually the reason for using these is dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating point numbers.\nComplex numbers These represent complex numbers as a pair of machine-level double precision floating point numbers. The same caveats apply as for floating point numbers. The real and imaginary value of a complex number `z` can be retrieved through the attributes `z.real` and `z.imag`.\nSequences These represent finite ordered sets indexed by natural numbers. The built-in function len() returns the number of items of a sequence. When the length of a sequence is `n`, the index set contains the numbers 0, 1, ..., `n`. Item `i` 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 sequence of the same type -- this implies that the index set is renumbered so that it starts at 0 again.\nSequences are distinguished according to their mutability:\nImmutable sequences An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however the array of objects directly referenced by an immutable object cannot change.)\nThe following types are immutable sequences:\nStrings The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0-127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g. to hold data read from a file.\n(What should be done on systems whose native character set is not ASCII???)\nTuples The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a 'singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by enclosing 'nothing' in parentheses: ''`()`''.\nMutable sequences Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment 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 by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)\nThe optional module `array` provides an additional example of a mutable sequence type.\nMappings These represent finite sets of objects indexed by arbitrary index sets. The subscript notation a[k] selects the item indexed by k from the mapping a; this can be used in expressions and as the target of assignments or del statements. The built-in function len() returns the number of items in a mapping.\nThere is currently a single intrinsic mapping type:\nDictionaries These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity -- the reason being that the efficient implementation of dictionaries requires a key's value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g. 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.\nDictionaries are mutable; they are created by the {...} notation. (See \"Dictionary displays\" on page 28. (ref-7.html#MARKER-9-33))\nThe optional library modules `dbm`, `gdbm` and `bsddb` provide additional examples of mapping types.\nCallable types These are the types to which the function call operation (for invocation, See \"Calls\" on page 31. (ref-10.html#MARKER-8-50)) is applied:\nUser-defined functions A user-defined function object is created by a function definition. (See \"Function definitions\" on page 50. (ref-9.html#MARKER-9-43))\nSpecial read-only attributes: `func_doc` or `__doc__` is the function's documentation string, or `None` if unavailable; `func_name` or `__name__` is the function's name; `func_defaults` is a tuple containing default argument values for those arguments that have defaults, or `None` if no arguments have a default value; func_code is the code object representing the compiled function body; func_globals is (a reference to) the dictionary that holds the function's global variables -- it defines the global name space of the module in which the function was defined. Additional information about a function's definition can be retrieved from its code object; see the description of internal types below.\nUser-defined methods A user-defined method object (a.k.a. object closure) combines a class, a class instance (or `None`) and a user-defined function.\nSpecial read-only attributes: im_self is the instance object; im_func is the function object; `im_class` is the class that defined the method (which may be a base class of the class of which `im_self` is an instance); `__doc__` is the method's documentation (same as `im_func.__doc__`); `__name__` is the method name (same as `im_func.__name__`).\nUser-defined method objects are created in two ways: when getting an attribute of a class that is a user-defined function object, or when getting an attributes of a class instance that is a user-defined function object. In the former case (class attribute), the `im_self` attribute is `None`, and the method object is said to be unbound; in the latter case (instance attribute), `im_self` is the instance, and the method object is said to be bound. For instance, when `C` is a class which contains a definition for a function `f`, `C.f` does not yield the function object `f`; rather, it yields an unbound method object m where `m.im_class` is `C`, `m.im_function` is `f`, and m`.im_self` is `None`. When `x` is a `C` instance, `x.f` yields a bound method object `m` where `m.im_class` is `C`, `m.im_function` is `f,` and `m.im_self` is `x`.\nWhen an unbound user-defined method object is called, the underlying function (`im_func`) is called, with the restriction that the first argument must be an instance of the proper class (`im_class`) or of a derived class thereof.\nWhen a bound user-defined method object is called, the underlying function (`im_func`) is called, inserting the class instance (`im_self`) in front of the argument list. For instance, when `C` is a class which contains a definition for a function `f`, and `x` is an instance of `C`, calling `x.f(1)` is equivalent to calling `C.f(x, 1)`.\nNote that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation.\nBuilt-in functions A built-in function object is a wrapper around a C function. Examples of built-in functions are len and math.sin (`math` is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes: `__doc__` is the function's documentation string, or `None` if unavailable; `__name__` is the function's name; `__self__` is set to `None` (but see the next paragraph).\nBuilt-in methods This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is list.append, assuming list is a list object. In this case, the special read-only attribute `__self__` is set to the object denoted by `list`.\nClasses Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class's __init__ method if it has one. Any arguments are passed on to the __init__ method -- if there is no __init__ method, the class must be called without arguments.\nClass instances Class instances are described below. Class instances can be called as a function only when the class has a `__call__` method; in this case, `x(arguments)` is a shorthand for `x.__call__(arguments)`.\nModules Modules are imported by the import statement. (See \"The import statement\" on page 43. (ref-8.html#MARKER-9-64)) A module object has a name space implemented by a dictionary object (this is the dictionary referenced by the func_globals attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g. `m.x` is equivalent to `m.__dict__[\"x\"]`. A module object does not contain the code object used to initialize the module (since it isn't needed once the initialization is done).\nAttribute assignment update the module's name space dictionary, e.g. ''`m.x = 1`'' is equivalent to ''`m.__dict__[\"x\"] = 1`''.\nSpecial read-only attribute: __dict__ is the dictionary object that is the module's name space.\nPredefined (writable) attributes: __name__ is the module name; __doc__ is the module's documentation string, or None if unavailable; `__file__` is the pathname of the file from which the module was loaded, if it was loaded from a file. The `__file__` attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.\nClasses Class objects are created by class definitions (See \"Class definitions\" on page 51. (ref-9.html#MARKER-9-48)). A class has a name space implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g. ''`C.x`'' is translated to ''`C.__dict__[\"x\"]`''. When the attribute name is not found there, the attribute search continues in the base classes. The search is depth-first, left-to-right in the order of their occurrence in the base class list. When a class attribute reference would yield a user-defined function object, it is transformed into an unbound user-defined method object (see above). The `im_class` attribute of this method object is the class in which the function object was found, not necessarily the class for which the attribute reference was initiated.\nClass attribute assignments update the class's dictionary, never the dictionary of a base class.\nA class object can be called as a function (see above) to yield a class instance (see below).\nSpecial read-only attributes: __dict__ is the dictionary that is the class's name space; `__name__` is the class name; __bases__ is a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list.\nPredefined (writable) attribute: `__doc__` is the class's documentation string, or `None` if undefined.\nClass instances A class instance is created by calling a class object as a function (see above). A class instance has a name space implemented as a dictionary, which is the first place where instance attributes are searched. When an attribute is not found there, the search continues with the class attributes. If a class attribute is found that is a user-defined function object (and in no other case), it is transformed into an unbound user-defined method object (see above). The `im_class` attribute of this method object is the class in which the function object was found, not necessarily the class of the instance for which the attribute reference was initiated. If no class attribute is found, and the object's class has a `__getattr__` method, that is called to satisfy the lookup.\nAttribute assignments and deletions update the instance's dictionary, never a class's dictionary. If the class has a `__setattr__` or `__delattr__` method, this is called instead of updating the instance dictionary directly.\nClass instances can pretend to be numbers, sequences, mappings, or callable objects, and override various other special operations, if they have methods with certain special names. See \"Special method names\" on page 18 (#MARKER-9-190).\nSpecial attributes: __dict__ yields the attribute dictionary; __class__ yields the instance's class. In some implementations these may be assigned a new value; the new value must have the same type as the old value.\nFiles A file object represents an open file. File objects are created by the open() built-in function, and also by os.popen(), os.fdopen() and the makefile() method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter's standard input, output and error streams. See the Python Library Reference for complete documentation of file objects.\nInternal types A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.\nCode objects Code objects represent byte-compile executable Python code, or bytecode. The difference between a code object and a function object is that the function object contains an explicit reference to the function's globals (the name space dictionary of the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.\nSpecial read-only attributes: `co_argcount` is the number of positional arguments (including arguments with default values); `co_nlocals` is the number of local variables used by the function (including arguments); `co_varnames` is a tuple containing the names of the local variables (starting with the argument names); co_code is a string representing the sequence of bytecode instructions; co_consts is a tuple containing the literals used by the bytecode; co_names is a tuple containing the names used by the bytecode; co_filename is the filename from which the code was compiled; `co_flags` is an integer encoding a number of flags for the interpreter. The following flag bits are defined: bit 2 is set if the function uses the \"`*arguments`'' syntax to accept an arbitrary number of positional arguments; bit 3 is set if the function uses the ''`**keywords`'' syntax to accept arbitrary keyword arguments; other bits are used internally or reserved for future use. The first item in `co_consts` is the documentation string of the function, or `None` if undefined. To find out the first line number of a function, you have to disassemble the bytecode instructions; the standard library module codehack defines a function `getlineno()` that returns the first line number of a code object.\nFrame objects Frame objects represent execution frames. They may occur in traceback objects (see below).\nSpecial read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up locals variables; f_globals is used for global variables; `f_builtins` is used for built-in (intrinsic) names; `f_restricted` is a flag indicating whether the function is executing in restricted execution mode; f_lineno gives the current line number and f_lasti gives the precise instruction (this is an index into the instruction string of the code object).\nSpecial writable attributes: `f_trace`, if not `None`, is a function called at the start of each source code line (this is used by the debugger).\nTraceback objects Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See \"The try statement\" on page 49. (ref-9.html#MARKER-9-30)) It is accessible as sys.exc_traceback, and also as the third item of the tuple returned by `sys.exc_info()`. The latter is the preferred interface, since it works correctly when the program is using multiple threads. When the program contains no suitable exception handler, the stack trace is printed on the standard error stream; if the interpreter is interactive, it is also made available to the user as sys.last_traceback.\nSpecial read-only attributes: tb_next is the next level in the stack trace (towards the frame where the exception occurred), or None if there is no next level; tb_frame points to the execution frame of the current level; tb_lineno gives the line number where the exception occurred; tb_lasti indicates the precise instruction. The line number and last instruction in the traceback may differ from the line number of its frame object if the exception occurred in a try statement with no matching except clause or with a finally clause.\nSlice objects Slice objects are used to represent slices when extended slice syntax is used (this is a slice using two colons, or multiple slices or ellipses separated by commas, e.g. `a[i:j:step]`, `a[i:j, k:l]`, or `a[..., i:j]`). They are also created by the built-in `slice()` function.\nSpecial read-only attributes: `start` is the lowerbound; `stop` is the upperbound; `step` is the step value; each is `None` if omitted. These attributes can have any type.\n## 3.3 Special method names\nThis section describes how user-defined classes can customize their behavior or emulate the behavior of other object types. In the following, if a class defines a particular method, any class derived from it is also understood to define that method (implicitly).\nA class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. For instance, if a class defines a method named __getitem__, and x is an instance of this class, then x[i] is equivalent to x.__getitem__(i). (The reverse is not true; e.g. if x is a list object, x.__getitem__(i) is not equivalent to x[i].) Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined.\n### 3.3.1 Basic customization\n__init__(self, [args...]) Called when the instance is created. The arguments are those that were passed to the class constructor expression. If a base class has an `__init__` method the derived class's `__init__` method must explicitly call it to ensure proper initialization of the base class part of the instance, e.g.\n''`BaseClass.__init__(self, [args...])`''.\n__del__(self) Called when the instance is about to be destroyed. If a base class has a `__del__` method the derived class's `__del__` method must explicitly call it to ensure proper deletion of the base class part of the instance. e.g. ''`BaseClass.__del__(self)`''. Note that it is possible (though not recommended!) for the `__del__` method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that `__del__` methods are called for objects that still exist when the interpreter exits.\nProgrammer's note: ''`del` `x`'' doesn't directly call `x.__del__()` -- the former decrements the reference count for `x` by one, and the latter is only called when its reference count reaches zero. Some common situations that may prevent the reference count of an object to go to zero include: circular references between objects (e.g. a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in `sys.exc_traceback` keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in `sys.last_traceback` keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the latter two situations can be resolved by storing `None` in `sys.exc_traceback` or `sys.last_traceback`.\nWarning: due to the precarious circumstances under which `__del__` methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to `sys.stderr` instead. Also, when `__del__` is invoked is response to a module being deleted (e.g. when execution of the program is done), other globals referenced by the `__del__` method may already have been deleted. For this reason, `__del__` methods should do the absolute minimum needed to maintain external invariants. Python 1.5 guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the `__del__` method is called.\n__repr__(self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the \"official\" string representation of an object. This should normally look like a valid Python expression that can be used to recreate an object with the same value.\n__str__(self) Called by the str() built-in function and by the print statement compute the ''informal'' string representation of an object. This differs from `__repr__` in that it doesn't have to look like a valid Python expression: a more convenient or concise representation may be used instead.\n__cmp__(self, other) Called by all comparison operations. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no `__cmp__` method is defined, class instances are compared by object identity (\"address\"). (Note: the restriction that exceptions are not propagated by `__cmp__` has been removed in Python 1.5)\n__hash__(self) Called for the key object for dictionary operations, and by the built-in function `hash()`. Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g. using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If no `__hash__` method is defined, class instances are hashed by object identity (''address''). If a class does not define a `__cmp__` method it should not define a `__hash__` method either; if it defines `__cmp__` but not `__hash__` its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a `__cmp__` method it should not implement `__hash__` since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket).\n__nonzero__(self) Called to implement truth value testing; should return 0 or 1. When this method is not defined, __len__ is called, if it is defined (see below). If a class defines neither __len__ nor __nonzero__, all its instances are considered true.\n### 3.3.2 Customizing attribute access\nThe following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of `x. name`) for class instances. For performance reasons, these methods are cached in the class object at class definition time; therefore, they cannot be changed after the class definition is executed.\n__getattr__(self, name) Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for `self`). `name` is the attribute name. This method should return the (computed) attribute value or raise an `AttributeError` exception.\nNote that if the attribute is found through the normal mechanism, __getattr__ is not called. (This is an intentional asymmetry between __getattr__ and __setattr__.) This is done both for efficiency reasons and because otherwise __setattr__ would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object).\n__setattr__(self, name, value) Called whenever an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. instead of storing the value in the instance dictionary). `name` is the attribute name, `value` is the value to be assigned to it.\nIf `__setattr__` wants to assign to an instance attribute, it should not simply execute ''`self. name = value`'' -- this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g.\n''`self. __dict__[name] = value`''.\n__delattr__(self, name) Like `__setattr__` but for attribute deletion instead of assignment.\n### 3.3.3 Emulating callable objects\n__call__(self, [args...]) Called when the instance is \"called\" as a function; if this method is defined, `x(arg1, arg2, ...)` is a shorthand for `x.__call__(arg1, arg2, ...)`.\n### 3.3.4 Emulating sequence and mapping types\nThe following methods can be defined to emulate sequence or mapping objects. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers k for which 0 `<=` k `<` N where N is the length of the sequence, and the method `__getslice__` (see below) should be defined. It is also recommended that mappings provide methods `keys`, `values` and `items` behaving similar to those for Python's standard dictionary objects; mutable sequences should provide methods `append`, `count`, `index`, `insert`, `sort`, `remove` and `reverse` like Python standard list objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods `__add__`, `__radd__`, `__mul__` and `__rmul__` described below; they should not define `__coerce__` or other numerical operators.\n__len__(self) Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a `__nonzero__()` method and whose __len__() method returns zero is considered to be false in a Boolean context.\n__getitem__(self, key) Called to implement evaluation of self[key]. Note that the special interpretation of negative keys (if the class wishes to emulate a sequence type) is up to the __getitem__ method.\n__setitem__(self, key, value) Called to implement assignment to self[key]. Same note as for __getitem__.\n__delitem__(self, key) Called to implement deletion of self[key]. Same note as for __getitem__.\n#### 3.3.4.1 Additional methods for emulation of sequence types\nThe following methods can be defined to further emulate sequence objects. For immutable sequences methods, only `__getslice__` should be defined; for mutable sequences, all three methods should be defined.\n__getslice__(self, i, j) Called to implement evaluation of self[i:j]. The returned object should be of the same type as `self`. Note that missing i or j in the slice expression are replaced by 0 or len(self), respectively, and len(self) has been added (once) to originally negative i or j by the time this function is called (unlike for __getitem__).\n__setslice__(self, i, j, sequence) Called to implement assignment to self[i:j]. The `sequence` argument can have any type. The return value should be `None`. Same notes for `i` and `j` as for __getslice__.\n__delslice__(self, i, j) Called to implement deletion of self[i:j]. Same notes for `i` and `j` as for __getslice__.\nNotice that these methods are only invoked when a single slice with a single colon is used. For slice operations involving extended slice notation, `__getitem__`, `__setitem__` or `__delitem__` is called.\n### 3.3.5 Emulating numeric types\nThe following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined.\n__add__(self, right)\n__sub__(self, right)\n__mul__(self, right)\n__div__(self, right)\n__mod__(self, right)\n__divmod__(self, right)\n__pow__(self, right)\n__lshift__(self, right)\n__rshift__(self, right)\n__and__(self, right)\n__xor__(self, right)\n`__or__(self, right)`These functions are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), <<, >>, &, ^, |). For instance: to evaluate the expression x+y, where x is an instance of a class that has an __add__ method, x.__add__(y) is called.\n__radd__(self, left)\n__rsub__(self, left)\n__rmul__(self, left)\n__rdiv__(self, left)\n__rmod__(self, left)\n__rdivmod__(self, left)\n__rpow__(self, left)\n__rlshift__(self, left)\n__rrshift__(self, left)\n__rand__(self, left)\n__rxor__(self, left)\n__ror__(self, left) These functions are called to implement the binary arithmetic operations (+, -, *, /, %, divmod(), pow(), <<, >>, &, ^, |) with reversed operands. These functions are only called if the left operand does not support the corresponding operation (possibly after coercion). For instance: to evaluate the expression x+y, where x is an instance of a class that does not have an `__add__` method, `y.__radd(x)` is called. If the class defines a __coerce__ method that coerces its arguments to a common type, these methods will never be called and thus needn't be defined. They are useful for classes that implement semi-numerical data types (types that have some numerical behavior but don't adhere to all invariants usually assumed about numbers).\n__neg__(self)\n__pos__(self)\n__abs__(self)\n__invert__(self) Called to implement the unary arithmetic operations (-, +, abs() and ~).\n__int__(self)\n__long__(self)\n__float__(self) Called to implement the built-in functions int(), long() and float(). Should return a value of the appropriate type.\n__oct__(self)\n__hex__(self) Called to implement the built-in functions oct() and hex(). Should return a string value.\n__coerce__(self, other) Called to implement \"mixed-mode\" numeric arithmetic. Should either return a 2-tuple containing `self` and `other` converted to a common numeric type, or `None` if no conversion is possible. When the common type would be the type of `other`, it is sufficient to return `None`, since the interpreter will also ask the other object to attempt a coercion (but sometimes, if the implementation of the other type cannot be changed, it is useful to do the conversion to the other type here).\nCoercion rules: to evaluate x op y, the following steps are taken (where `__op__` and `__rop__` are the method names corresponding to op, e.g. if op is '`+`', `__add__` and `__radd__` are used). If an exception occurs at any point, the evaluation is abandoned and exception handling takes over.\n0. If x is a string object and op is the modulo operator (`%`), the string formatting operation (see [Ref:XXX]) is invoked and the remaining steps are skipped.\n1. If x is a class instance:\n1a. If x has a `__coerce__` method: replace x and y with the 2-tuple returned by `x.__coerce__(y)`; skip to step 2 if the coercion returns `None`.\n1b. If neither x nor y is a class instance after coercion, go to step 3.\n1c. If x has a method `__op__`, return `x.__op__(y)`; otherwise, restore x and y to their value before step 1a.\n2. If y is a class instance:\n2a. If y has a `__coerce__` method: replace y and x with the 2-tuple returned by `y.__coerce__(x)`; skip to step 3 if the coercion returns None.\n2b. If neither x nor y is a class instance after coercion, go to step 3.\n2b. If y has a method `__rop__`, return `y.__rop__(x)`; otherwise, restore x and y to their value before step 2a.\n3. We only get here if neither x nor y is a class instance.\n3a. If op is '`+`' and x is a sequence, sequence concatenation is invoked.\n3b. If op is '`*`' and one operand is a sequence and the other an integer, sequence repetition is invoked.\n3c. Otherwise, both operands must be numbers; they are coerced to a common type if possible, and the numeric operation is invoked for that type.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-6.html)[Previous] (ref-4.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 40546, "url": "https://docs.python.org/1.5/ref/ref-5.html"} {"title": "Chapter 4: Execution model", "text": "[Next] (ref-7.html)[Previous] (ref-5.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 4: Execution model\n---\n## 4.1 Code blocks, execution frames, and name spaces\nA code block is a piece of Python program text that can be executed as a unit, such as a module, a class definition or a function body. Some code blocks (like modules) are normally executed only once, others (like function bodies) may be executed many times. Code blocks may textually contain other code blocks. Code blocks may invoke other code blocks (that may or may not be textually contained in them) as part of their execution, e.g. by invoking (calling) a function.\nThe following are code blocks: A module is a code block. A function body is a code block. A class definition is a code block. Each command typed interactively is a separate code block; a script file (a file given as standard input to the interpreter or specified on the interpreter command line the first argument) is a code block; a script command (a command specified on the interpreter command line with the '-c' option) is a code block. The string argument passed to the built-in function eval and to the exec statement are code blocks. The file read by the built-in function `execfile` is a code block. And finally, the expression read and evaluated by the built-in function input is a code block. A code block is executed in an execution frame. An execution frame contains some administrative information (used for debugging), determines where and how execution continues after the code block's execution has completed, and (perhaps most importantly) defines two name spaces, the local and the global name space, that affect execution of the code block.\nA name space is a mapping from names (identifiers) to objects. A particular name space may be referenced by more than one execution frame, and from other places as well. Adding a name to a name space is called binding a name (to an object); changing the mapping of a name is called rebinding; removing a name is unbinding. Name spaces are functionally equivalent to dictionaries (and often implemented as dictionaries).\nThe local name space of an execution frame determines the default place where names are defined and searched. The global name space determines the place where names listed in global statements are defined and searched, and where names that are not bound anywhere in the current code block are searched.\nWhether a name is local or global in a code block is determined by static inspection of the source text for the code block: in the absence of global statements, a name that is bound anywhere in the code block is local in the entire code block; all other names are considered global. The global statement forces global interpretation of specified names throughout the code block. The following constructs bind names: formal parameters to functions, import statements, class and function definitions (these bind the class or function name in the defining block), and targets that are identifiers if occurring in an assignment, for loop header, or in the second position of an except clause header. Local names are searched only on the local name space; global names are searched only in the global and built-in namespace.[1] (#FOOTNOTE-1)\nA target occurring in a del statement is also considered bound for this purpose (though the actual semantics are to \"unbind\" the name).\nWhen a global name is not found in the global name space, it is searched in the built-in namespace. The built-in namespace associated with the execution of a code block is actually found by looking up the name `__builtins__` is its global name space; this should be a dictionary or a module (in the latter case its dictionary is used). Normally, the `__builtins__` namespace is the dictionary of the built-in module `__builtin__` (note: no 's'); if it isn't, restricted execution mode is in effect, see [Ref:XXX]. When a name is not found at all, a NameError exception is raised.\nThe following table lists the local and global name space used for all types of code blocks. The name space for a particular module is automatically created when the module is first imported. Note that in almost all cases, the global name space is the name space of the containing module -- scopes in Python do not nest!\nNotes:\nn.s. means name space\n(1) The main module for a script is always called `__main__`; ''the filename don't enter into it.''\n(2) The global and local name space for these can be overridden with optional extra arguments.\n(3) The `exec` statement and the `eval()` and `execfile()` functions have optional arguments to override the global and local namespace. If only one namespace is specified, it is used for both.\nThe built-in functions globals() and locals() returns a dictionary representing the current global and local name space, respectively. The effect of modifications to this dictionary on the name space are undefined.[2] (#FOOTNOTE-2)\n## 4.2 Exceptions\nExceptions are a means of breaking out of the normal flow of control of a code block in order to handle errors or other exceptional conditions. An exception is raised at the point where the error is detected; it may be handled by the surrounding code block or by any code block that directly or indirectly invoked the code block where the error occurred.\nThe Python interpreter raises an exception when it detects a run-time error (such as division by zero). A Python program can also explicitly raise an exception with the raise statement. Exception handlers are specified with the try...except statement. The `try`...`finally` statement specifies cleanup code which does not handle the exception, but is executed whether an exception occurred or not in the preceding code.\nPython uses the \"termination\" model of error handling: an exception handler can find out what happened and continue execution at an outer level, but it cannot repair the cause of the error and retry the failing operation (except by re-entering the the offending piece of code from the top).\nWhen an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. In this case, the interpreter normally prints a stack backtrace.\nExceptions are identified by string objects or class instances. Selection of a matching `except` clause is based on object identity (i.e. two different string objects with the same value represent different exceptions). For string exceptions, the except clause must reference the same string object. For class exceptions, the except clause must reference the same class or a base class of it.\nWhen an exception is raised, an object (maybe None) is passed as the exception's \"parameter\" or ''value''; this object does not affect the selection of an exception handler, but is passed to the selected exception handler as additional information. For class exceptions, this object must be an instance of the exception class being raised.\nSee also the description of the try and raise statements in \"Compound statements\" on page 47 (ref-9.html#MARKER-9-1).\n---\n[1] If the code block contains exec statements or the construct ''from ... import *'', the semantics of local names change subtly: local name lookup first searches in the local namespace, then in the global namespace and in the built-in namespace.\n---\n[2] The current implementations return the dictionary actually used to implement the name space, except for functions, where the optimizer may cause the local name space to be implemented differently, and locals() returns a dictionary that is a shadow copy of the actual local name space.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-7.html)[Previous] (ref-5.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 7876, "url": "https://docs.python.org/1.5/ref/ref-6.html"} {"title": "Chapter 5: Expressions", "text": "[Next] (ref-8.html)[Previous] (ref-6.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 5: Expressions\n---\nThis chapter explains the meaning of the elements of expressions in Python.\nSyntax notes: in this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. 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`.\n## 5.1 Arithmetic conversions\nWhen a description of an arithmetic operator below uses the phrase \"the numeric arguments are converted to a common type\", the arguments are coerced using the coercion rules listed at the end of chapter 3 (ref-5.html#MARKER-9-9). If both arguments are standard numeric types, the following coercions are applied:\n- If either argument is a complex number, the other is converted to complex;\notherwise, if either argument is a floating point number, the other is converted to floating point;\notherwise, if either argument is a long integer, the other is converted to long integer;\notherwise, both must be plain integers and no conversion is necessary.\nSome additional rules apply for certain operators (e.g. a string left argument to the '`%`' operator). Extensions can define their own coercions.\n## 5.2 Atoms\nAtoms are the most basic elements of expressions. The simplest atoms are identifiers or literals. Forms enclosed in reverse quotes or in parentheses, brackets or braces are also categorized syntactically as atoms. The syntax for atoms is:\n```text\n\natom\n: identifier | literal | enclosure\n\nenclosure: par\nenth_form|list_display|dict_display|string_conversion\n```\n### 5.2.1 Identifiers (Names)\nAn identifier occurring as an atom is a reference to a local, global or built-in name binding. If a name is assigned to anywhere in a code block (even in unreachable code), and is not mentioned in a `global` statement in that code block, then it refers to a local name throughout that code block. When it is not assigned to anywhere in the block, or when it is assigned to but also explicitly listed in a `global` statement, it refers to a global name if one exists, else to a built-in name (and this binding may dynamically change).\nWhen the name is bound to an object, evaluation of the atom yields that object. When a name is not bound, an attempt to evaluate it raises a `NameError` exception.\nPrivate name mangling: when an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a \"private name\" of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.\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, integer, long integer, floating point number, complex number) with the given value. The value may be approximated in the case of floating point and imaginary (complex) literals. (See \"Literals\" on page 6 (ref-4.html#MARKER-9-47) for details.)\nAll literals correspond to immutable data types, and hence the object's identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.\n### 5.2.3 Parenthesized forms\nA parenthesized form is an optional expression list enclosed in parentheses:\n```text\n\nparenth_form: \"(\" [expression_list] \")\"\n```\nA parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.\nAn empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply(i.e., two occurrences 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 of the comma operator. The exception is the empty tuple, for which parentheses are required -- allowing unparenthesized \"nothing\" in expressions would cause ambiguities and allow common typos to pass uncaught.\n### 5.2.4 List displays\nA list display is a possibly empty series of expressions enclosed in square brackets:\n```text\n\nlist_display: \"[\" [expression_list] \"]\"\n```\nA list display yields a new list object. If it has no expression list, the list object has no items. Otherwise, the elements of the expression list are evaluated from left to right and inserted in the list object in that order.\n### 5.2.5 Dictionary displays\nA dictionary display is a possibly empty series of key/datum pairs enclosed 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 entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum.\nRestrictions on the types of the key values are listed earlier in \"The standard type hierarchy\" on page 12 (ref-5.html#MARKER-9-34) (to summarize, the key type should be hashable, which excludes all mutable objects). Clashes between duplicate keys are not detected; the last datum (textually rightmost in the display) stored for a given key value prevails.\n### 5.2.6 String conversions\nA string conversion is an expression list enclosed in reverse (a.k.a. backward) quotes:\n```text\n\nstring_conversion: \"'\" expression_list \"'\"\n```\nA string conversion evaluates the contained expression list and converts the resulting object into a string according to rules specific to its type.\nIf the object is a string, a number, `None`, or a tuple, list or dictionary containing only objects whose type is one of these, the resulting string is a valid Python expression which can be passed to the built-in function `eval()` to yield an expression with the same value (or an approximation, if floating point numbers are involved).\n(In particular, converting a string adds quotes around it and converts \"funny\" characters to escape sequences that are safe to print.)\nIt is illegal to attempt to convert recursive objects (e.g. lists or dictionaries that contain a reference to themselves, directly or indirectly.)\nThe built-in function `repr()` performs exactly the same conversion in its argument as enclosing it in parentheses and reverse quotes does. The built-in function `str()` performs a similar but more user-friendly conversion.\n## 5.3 Primaries\nPrimaries represent the most tightly bound operations of the language. Their syntax is:\n```text\n\nprimary: atom | attributeref | subscription | slicing | call\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 attribute references. This object is then asked to produce the attribute whose name is the identifier. If this attribute is not available, the exception `AttributeError` is raised. Otherwise, the type and value of the object produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects.\n### 5.3.2 Subscriptions\nA subscription selects an item of a sequence (string, tuple or list) or 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 object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key.\nIf the primary is a sequence, the expression (list) must evaluate to a plain integer. If this value is negative, the length of the sequence is added to it (so that, e.g. `x[-1]` selects the last item of `x`.) The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero).\nA string's items are characters. A character is not a separate data type but a string of exactly one character.\n### 5.3.3 Slicings\nA slicing selects a range of items in a sequence (string, tuple or list) object. Slicings may be used as expressions or as targets 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's an ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by declaring that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice nor ellipses). Similarly, when the slice list has exactly one short slice and no trailing comma, the interpretation as a simple slicing takes priority over that as an extended slicing.\nThe semantics for a simple slicing are as follows. The primary must evaluate to a sequence object. The lower and upper bound expressions, if present, must evaluate to plain integers; defaults are zero and the sequence's length, respectively. If either bound is negative, the sequence's length is added to it. The slicing now selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds. This may be an empty sequence. It is not an error if i or j lie outside the range of valid indexes (such items don't exist so they aren't selected).\nThe semantics for an extended slicing are as follows. The primary must evaluate to a mapping object, and it is indexed with a key that is constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple containing the conversion of the slice items; otherwise, the conversion of the lone slice item is the key. The conversion of a slice item that is an expression is that expression. The conversion of an ellipsis slice item is the built-in `Ellipsis` object. The conversion of a proper slice is a slice object (see page 17 (ref-5.html#MARKER-9-187)) whose `start`, `stop` and `step` attributes are the values of the expressions given as lower bound, upper bound and stride, respectively, substituting `None` for missing expressions.\n### 5.3.4 Calls\nA call calls a callable object (e.g. a function) with a possibly empty series 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 affect the semantics.\nThe primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and certain class instances themselves are callable; extensions may define additional callable object types). All argument expressions are evaluated before the call is attempted. Please refer to \"Function definitions\" on page 50 (ref-9.html#MARKER-9-43) for the syntax of formal parameter lists.\nIf keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a `TypeError` exception is raised. Otherwise, the value of the argument is placed in the slot, filling it (even if the expression is `None`, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a `TypeError` exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.\nIf there are more positional arguments than there are formal parameter slots, a `TypeError` exception is raised, unless a formal parameter using the syntax''`*identifier`'' is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).\nIf any keyword argument does not correspond to a formal parameter name, a `TypeError` exception is raised, unless a formal parameter using the syntax ''`**identifier`'' is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.\nFormal parameters using the syntax ''`*identifier`'' or ''`**identifier`'' cannot be used as positional argument slots or as keyword argument names. Formal parameters using the syntax ''`(sublist)`'' cannot be used as keyword argument names; the outermost sublist corresponds to a single unnamed argument slot, and the argument value is assigned to the sublist using the usual tuple assignment rules after all other parameter processing is done.\nA call always returns some value, possibly `None`, unless it raises an exception. How this value is computed depends on the type of the callable object.\nIf it is:\na user-defined function: the code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section\"Function definitions\" on page 50 (ref-9.html#MARKER-9-43). When the code block executes a `return` statement, this specifies the return value of the function call.\na built-in function or method: the result is up to the interpreter; see the library reference manual for the descriptions of built-in functions and methods.\na class object: a new instance of that class is returned.\na class instance method: the corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call. The instance becomes the first argument.\n## 5.4 The power operator\nThe power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:\n```text\n\npower: primary [\"**\" u_expr]\n```\nThus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands).\nThe power operator has the same semantics as the built-in `pow()` function: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common type. The result type is that of the arguments after coercion; if the result is not expressible in that type (as in raising an integer to a negative power, or a negative floating point number to a broken power), a `TypeError` exception is raised.\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 numeric argument.\nThe unary `\"+\"` (plus) operator yields its numeric argument unchanged.\nThe unary `\"~\"` (invert) operator yields the bit-wise inversion of its plain or long integer argument. The bit-wise inversion of `x` is defined as `-(x+1)`. It only applies to integral numbers.\nIn all three cases, if the argument does not have the proper type, a `TypeError` exception is raised.\n## 5.6 Binary arithmetic operations\nThe remaining binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators:\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 arguments. The arguments must either both be numbers, or one argument must be a plain integer and the other must be a sequence. In the former case, the numbers are converted to a common type and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.\nThe \"`/`\" (division) operator yields the quotient of its arguments. The numeric arguments are first converted to a common type. Plain or long integer division yields an integer of the same type; the result is that of mathematical division with the 'floor' function applied to the result. Division by zero raises the `ZeroDivisionError` exception\nThe \"`%`\" (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the `ZeroDivisionError` exception. The arguments may be floating point numbers, e.g. `3.14%0.7` equals `0.34` (since `3.14` equals `4*0.7+0.34`). The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the second operand.\nThe integer division and modulo operators are connected by the following identity: `x == (x/y)*y + (x%y)`. Integer division and modulo are also connected with the built-in function `divmod()`: `divmod(x, y) == (x/y, x%y)`. These identities don't hold for floating point and complex numbers; there a similar identity holds where `x/y` is replaced by `floor(x/y)`) or\n`floor((x/y).real)`, respectively.\nThe `\"+\"` (addition) operator yields the sum of its arguments. The arguments must either both be numbers, or both sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated.\nThe `\"-\"` (subtraction) operator yields the difference of its arguments. The numeric arguments are first converted to a common type.\n## 5.7 Shifting operations\nThe shifting operations have lower priority than the arithmetic operations:\n```text\n\nshift_expr: a_expr | shift_expr ( \"<<\" | \">>\" ) a_expr\n```\nThese operators accept plain or long integers as arguments. The arguments are converted to a common type. They shift the first argument to the left or right by the number of bits given by the second argument.\nA right shift by n bits is defined as division by `pow(2,`n). A left shift by n bits is defined as multiplication with `pow(2,`n); for plain integers there is no overflow check so this drops bits and flips the sign if the result is not less than `pow(2,31)` in absolute value. Negative shift counts raise a `ValueError` exception.\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 bit-wise AND of its arguments, which must be plain or long integers. The arguments are converted to a common type.\nThe `\"^\"` operator yields the bitwise XOR (exclusive OR) of its arguments, which must be plain or long integers. The arguments are converted to a common type.\nThe `\"|\"` operator yields the bitwise (inclusive) OR of its arguments, which must be plain or long integers. The arguments are converted to a common type.\n## 5.9 Comparisons\nContrary to C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also contrary to C, expressions like `a < b < c` have the interpretation that is conventional in mathematics:\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 equivalent to `x < y and y <= z,`except that `y` is evaluated only once (but in both cases `z` is not evaluated at all when `x < y` is found to be false).\nFormally, if a, b, c, ..., y, z are expressions and opa, opb, ..., opy are comparison operators, then a opa b opb c ... y opy z is equivalent to a opa b `and b opb c` `and` ... y 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 between a and c, so that e.g. `x < y > z` is perfectly legal (though perhaps not pretty).\nThe forms `<>` and `!=` are equivalent; for consistency with C, `!=` is preferred; where `!=` is mentioned below `<>` is also implied.\nThe operators `\"<\", \">\", \"==\", \">=\", \"<=\"`, and `\"!=\"` compare the values of two objects. The objects needn't have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. (This unusual definition of comparison is done to simplify the definition of operations like sorting and the `in` and `not` `in` operators.)\nComparison of objects of the same type depends on the type:\n- Numbers are compared arithmetically.\nStrings are compared lexicographically using the numeric equivalents (the result of the built-in function `ord`) of their characters.\nTuples and lists are compared lexicographically using comparison of corresponding items.\nMappings (dictionaries) are compared through lexicographic comparison of their sorted (key, value) lists.[3] (#FOOTNOTE-3)\nMost other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.\nThe operators `in` and `not in` test for sequence membership: if y is a sequence, x in y is true if and only if there exists an index i such that x = y[i]. x not in y yields the inverse truth value. The exception `TypeError` is raised when y is not a sequence, or when y is a string and x is not a string of length one.[4] (#FOOTNOTE-4)\nThe operators `is` and `is not` test for object identity: x `is` y is true if and only if x and y are the same object. x `is not` y yields the inverse truth value.\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 used by control flow statements, the following values are interpreted as false: `None`, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true.\nThe operator `not` yields 1 if its argument is false, 0 otherwise.\nThe expression x `and` y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.\nThe expression x `or` y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.\n(Note that neither `and` nor `or` restrict the value and type they return to 0 and 1, but rather return the last evaluated argument. This is sometimes useful, e.g. if `s` is a string that should be replaced by a default value if it is empty, the expression `s or 'foo'` yields the desired value. Because `not` has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g. `not 'foo'` yields `0`, not `''`.)\nLambda forms (lambda expressions) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression `lambda` arguments`:` expression yields a function object that behaves virtually identical to one defined with\n```text\n\ndef name (arguments):\nreturn expression\n```\nSee \"Function definitions\" on page 50 (ref-9.html#MARKER-9-43) for the syntax of parameter lists. Note that functions created with lambda forms cannot contain statements.\n## 5.11 Expression lists\n```text\n\nexpression_list: expression (\",\" expression)* [\",\"]\n```\nAn expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.\nThe trailing comma is required only to create a single tuple (a.k.a. a single); it is optional in all other cases. A single expression without a trailing comma doesn't create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: `()`.)\n## 5.12 Summary\nThe following table summarizes the operator precedences in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for comparisons, which chain from left to right -- see above).\n---\n[3] This is expensive since it requires sorting the keys first, but about the only sensible definition. An earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to `{}`.\n---\n[4] The latter restriction is sometimes a nuisance.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-8.html)[Previous] (ref-6.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 27694, "url": "https://docs.python.org/1.5/ref/ref-7.html"} {"title": "Chapter 6: Simple statements", "text": "[Next] (ref-9.html)[Previous] (ref-7.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 6: Simple statements\n---\nSimple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by 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```\n## 6.1 Expression statements\nExpression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful result; in Python, procedures return the value None). Other uses of expression statements are allowed and occasionally 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 single expression). In interactive mode, if the value is not None, it is converted to a string using the built-in `repr()` function and the resulting string is written to standard output (see \"The print statement\" on page 42 (#MARKER-9-38)) on a line by itself. (Expression statements yielding `None` are not written, so that procedure calls do not cause any output.)\n## 6.2 Assert statements\nAssert statements are a convenient way to insert debugging 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\nexpression\n: raise AssertionError\n```\nThe extended form, \"`assert expression1, expression2`\", is equivalent to\n```text\n\nif __debug__:\nif not\nexpression1\n: raise AssertionError,\nexpression2\n```\nThese equivalences assume that `__debug__` and `AssertionError` refer to the built-in variables with those names. In the current implementation, the built-in variable `__debug__` is 1 under normal circumstances, 0 when optimization is requested (command line option `-O`). The current code generator emits no code for an `assert` statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.\n## 6.3 Assignment statements\nAssignment statements are used to (re)bind names to values and to modify attributes or items of mutable objects:\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 \"Primaries\" on page 29 (ref-7.html#MARKER-9-43) for the syntax definitions for the last three symbols.)\nAn assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.\nAssignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (See \"The standard type hierarchy\" on page 12. (ref-5.html#MARKER-9-34))\nAssignment of an object to a target list is recursively defined as follows.\n- If the target list is a single target: the object is assigned to that target.\nIf the target list is a comma-separated list of targets: the object must be a sequence with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. (This rule has been relaxed since Python 1.5; in earlier versions, the object had to be a tuple. Since strings are sequences, an assignment like \"a, b = \"xy\"\" is now legal.)\nAssignment of an object to a single target is recursively defined as follows.\n- If the target is an identifier (name):\nIf the name does not occur in a global statement in the current code block: the name is bound to the object in the current local name space.\nOtherwise: the name is bound to the object in the current global name space.\n- If the target is a target list enclosed in parentheses or square brackets: the object must be a sequence with the same number of items there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.\nIf the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; if this is not the case, TypeError is raised. That object is then asked to assign the assigned object to the given attribute; if it cannot perform the assignment, it raises an exception (usually but not necessarily AttributeError).\nIf the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (e.g. a list) or a mapping object (e.g. a dictionary). Next, the subscript expression is evaluated.\n- If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (e.g. a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence's length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence's length is added to it. The resulting bounds are clipped to lie between zero and the sequence's length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.\n(In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation phase, causing less detailed error messages.)\nWarning: Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are 'safe' (e.g. ''a, b = b, a'' swaps two variables), overlaps within the collection of assigned-to variables are not safe! For instance, the following program prints ''`[0, 2]`'':\n```text\n\nx = [0, 1]\ni = 0\ni, x[i] = 1, 2\nprint x\n```\n## 6.4 The pass statement\n```text\n\npass_stmt: \"pass\"\n```\npass is a null operation -- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:\n```text\n\ndef f(arg): pass # a function that does nothing (yet)\nclass C: pass # a class with no methods (yet)\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 defined. Rather that spelling it out in full details, here are some hints.\nDeletion of a target list recursively deletes each target, from left to right.\nDeletion of a name removes the binding of that name (which must exist) from the local or global name space, depending on whether the name occurs in a global statement in the same code block.\nDeletion of attribute references, subscriptions and slicings is passed to the primary object involved; deletion of a slicing is in general equivalent to assignment of an empty slice of the right type (but even this is determined by the sliced object).\n## 6.6 The print statement\n```text\n\nprint_stmt: \"print\" [ expression (\",\" expression)* [\",\"] ]\n```\nprint evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case: (1) when no characters have yet been written to standard output; or (2) when the last character written to standard output is \\n; or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.)\nA \"\\n\" character is written at the end, unless the print statement ends with a comma. This is the only action if the statement contains just the keyword print. Standard output is defined as the object named stdout in the built-in module sys. If no such object exists, or if it does not have a `write()` method, an exception is raised.\n## 6.7 The return statement\n```text\n\nreturn_stmt: \"return\" [expression_list]\n```\nreturn may only occur syntactically nested in a function definition, 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 list (or None) as return value.\nWhen return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.\n## 6.8 The raise statement\n```text\n\nraise_stmt: \"raise\" expression [\",\" expression [\",\" expression]]\n```\nraise evaluates its first expression, which must yield a string, class, or instance object. If there is a second expression, this is evaluated, else None is substituted. If the first expression is a class object, then the second expression must be an instance of that class or one of its derivatives. If the first expression is an instance object, the second expression must be None.\nIf the first object is a class or string, it then raises the exception identified by the first object, with the second one (or None) as its parameter. If the first object is an instance, it raises the exception identified by the class of the object, with the instance as its parameter (and there should be no second object, or the second object should be None).\nIf a third object is present, and it is not None, it should be a traceback object (see page 17 (ref-5.html#MARKER-9-175) traceback objects), and it is substituted instead of the current location as the place where the exception occurred. This is useful to re-raise an exception transparently in an except clause.\n## 6.9 The break statement\n```text\n\nbreak_stmt: \"break\"\n```\nbreak may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop.\nIt terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.\nIf a for loop is terminated by break, the loop control target keeps its current value.\nWhen break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.\n## 6.10 The continue statement\n```text\n\ncontinue_stmt: \"continue\"\n```\ncontinue may only occur syntactically nested in a for or while loop, but not nested in a function or class definition or try statement within that loop.[5] (#FOOTNOTE-5) It continues with the next cycle of the nearest enclosing loop.\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 initialize it if necessary; (2) define a name or names in the local name space (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly.\nThe system maintains a table of modules that have been initialized, indexed by module name. (The current implementation makes this table accessible as sys.modules.) When a module name is found in this table, step (1) is finished. If not, a search for a module definition is started. When a module is found, it is loaded. Details of the module searching and loading process are implementation and platform specific. It generally involves searching for a \"built-in\" module with the given name and then searching a list of locations given as `sys.path`.\nWhen step (1) finishes without raising an exception, step (2) can begin.\nThe first form of import statement binds the module name in the local name space to the module object, and then goes on to import the next identifier, if any. The from form does not bind the module name: it goes through the list of identifiers, looks each one of them up in the module found in step (1), and binds the name in the local name space to the object thus found. If a name is not found, ImportError is raised. If the list of identifiers is replaced by a star (*), all names defined in the module are bound, except those beginning with an underscore(_).\nNames bound by import statements should not occur in global statements in the same scope.\nThe from form with * should only occur in a module scope.\n(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)\nHierarchical module names: when the module names contains aone or more dots, the module search path is carried out differently. The sequence of identifiers up to the last dot is used to find a \"package\"; the final identifier is then searched inside the package. [XXX Can't be bothered to spell this out right now; see the URL http://grail.cnri.reston.va.us/python/essays/packages.hmtl for more details, also about how the module search works from inside a package.]\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 entire current code block. It means that the listed identifiers are to be interpreted as globals. While using global names is automatic if they are not defined in the local scope, assigning to global names would be impossible without global.\nNames listed in a global statement must not be used in the same code block before that global statement is executed.\nNames listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.\n(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)\nProgrammer's note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. In particular, a global statement contained in an exec statement does not affect the code block containing the exec statement, and code contained in an exec statement is unaffected by global statements in the code containing the exec statement. The same applies to the eval(), execfile() and compile() functions.\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 expression should evaluate to either a string, an open file object, or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). If it is an open file, the file is parsed until EOF and executed. If it is a code object, it is simply executed.\nIn all cases, if the optional parts are omitted, the code is executed in the current scope. If only the first expression after in is specified, it should be a dictionary, which will be used for both the global and the local variables. If two expressions are given, both must be dictionaries and they are used for the global and local variables, respectively.\nProgrammer's hints: dynamic evaluation of expressions is supported by the built-in function eval(). The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use by exec. When assigning to a global variable, a `global` statement for that variable should be present in the source code string passed to the `exec` statement.\n---\n[5] Except that it may currently occur within an except clause.\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-9.html)[Previous] (ref-7.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 16918, "url": "https://docs.python.org/1.5/ref/ref-8.html"} {"title": "Chapter 7: Compound statements", "text": "[Next] (ref-10.html)[Previous] (ref-8.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nPython 1.5 Reference Manual\n# Chapter 7: Compound statements\n---\nCompound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line.\nThe if, while and for statements implement traditional control flow constructs. try specifies exception handlers and/or cleanup code for a group of statements. Function and class definitions are also syntactically compound statements.\nCompound statements consist of one or more 'clauses'. A clause consists of a header and a 'suite'. The clause headers of a particular compound statement are all at the same indentation level. Each clause header begins with a uniquely identifying keyword and ends with a colon. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header's colon, or it can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn't be clear to which if clause a following else clause would belong:\n```text\n\nif test1: if test2: print x\n```\nAlso note that the semicolon binds tighter than the colon in this context, so that in the following example, either all or none of the print 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 NEWLINE possibly followed by a DEDENT. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the 'dangling else' problem is solved in Python by requiring nested if statements to be indented).\nThe formatting of the grammar rules in the following sections places each clause on a separate line for clarity.\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 by one until one is found to be true (see section \"Boolean operations\" on page 35 (ref-7.html#MARKER-9-116) for the definition of true and false); then that suite is executed (and no other part of the if statement is executed or evaluated). If all expressions are false, the suite of the else clause, if present, is executed.\n## 7.2 The `while` statement\nThe while statement is used for repeated execution as long as 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 first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.\nA break statement executed in the first suite terminates the loop without executing the else clause's suite. A continue statement executed in the first suite skips the rest of the suite and goes back to testing the expression.\n## 7.3 The `for` statement\nThe for statement is used to iterate over the elements of a sequence (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 suite is then executed once for each item in the sequence, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.\nA break statement executed in the first suite terminates the loop without executing the else clause's suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.\nThe suite may assign to the variable(s) in the target list; this does not affect the next item assigned to it.\nThe target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop. Hint: the built-in function range() returns a sequence of integers suitable to emulate the effect of Pascal's for i := a to b do; e.g. range(3) returns the list [0, 1, 2].\nWarning: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.\n```text\n\nfor x in a[:]:\nif x < 0: a.remove(x)\n```\n## 7.4 The `try` statement\nThe try statement specifies exception handlers and/or cleanup code 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: try...except and try...finally. These forms cannot be mixed (but they can be nested in each other).\nThe try...except form specifies one or more exception handlers (the except clauses). When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is \"compatible\" with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception. Note that the object identities must match, i.e. it must be the same object, not just an object with the same value.\nIf no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack.\nIf the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is cancelled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception).\nWhen a matching except clause is found, the exception's parameter is assigned to the target specified in that except clause, if present, and the except clause's suite is executed. When the end of this suite is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)\nBefore an except clause's suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc_type receives the object identifying the exception; sys.exc_value receives the exception's parameter; sys.exc_traceback receives a traceback object (see page 17 (ref-5.html#MARKER-9-175)) identifying the point in the program where the exception occurred. These details are also available through the `sys.exc_info()` function, which returns a tuple `(exc_type, exc_value, exc_traceback)`. Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. (As of Python 1.5, the variables are restored to their old values when returning from a function that handled an exception.)\nThe optional else clause is executed when no exception occurs in the try clause. Exceptions in the else clause are not handled by the preceding except clauses.\nThe try...finally form specifies a 'cleanup' handler. The try clause is executed. When no exception occurs, the finally clause is executed. When an exception occurs in the try clause, the exception is temporarily saved, the finally clause is executed, and then the saved exception is re-raised. If the finally clause raises another exception or executes a return, break or continue statement, the saved exception is lost. The exception information is not available to the program during execution of the finally clause.\nWhen a return or break statement is executed in the try suite of a try...finally statement, the finally clause is also executed 'on the way out'. A continue statement is illegal in the try clause. (The reason is a problem with the current implementation -- this restriction may be lifted in the future).\n## 7.5 Function definitions\nA function definition defines a user-defined function object (see \"The standard type hierarchy\" on page 12 (ref-5.html#MARKER-9-34)):\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 the function name in the current local name space to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global name space as the global name space to be used when the function is called.\nThe function definition does not execute the function body; this gets executed only when the function is called.\nWhen one or more top-level parameters have the form parameter = expression, the function is said to have \"default parameter values\". Default parameter values are evaluated when the function definition is executed. For a parameter with a default value, the correponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value -- this is a syntactic restriction that is not expressed by the grammar.[6] (#FOOTNOTE-6)\nFunction call semantics are described in more detail in section \"Calls\" on page 31 (ref-10.html#MARKER-8-50). A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form \"*identifier\" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form \"**identifier\" is present, it is initialized to a new dictionary receiving anyt excess keyword arguments, defaulting to a new empty dictionary.\nIt is also possible to create anonymous functions (functions not initially bound to a name), for immediate use in expressions. This uses lambda forms, described in section \"Boolean operations\" on page 35 (ref-7.html#MARKER-9-116). Note that the lambda form is merely a shorthand for a simplified function definition; a function defined in a \"def\" statement can be passed around or assigned to another name just like a function defined by a lambda form. The \"def\" form is actually more powerful since it allows the execution of multiple statements.\nProgrammer's note: A \"def\" form executed inside a function definition defines a local function that can be returned or passed around. Because of Python's two-scope philosophy, a local function defined in this way does not have access to the local variables of the function that contains its definition; the same rule applies to functions defined by a lambda form. A standard trick to pass selected local variables into a locally defined function is to use default argument values, like this:\n```text\n\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\n\nadd1 = make_incrementer(1)\nprint add1(3) # This prints '4'\n```\n## 7.6 Class definitions\nA class definition defines a class object (see section \"The standard type hierarchy\" on page 12 (ref-5.html#MARKER-9-34)):\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 inheritance list, if present. Each item in the inheritance list should evaluate to a class object. The class's suite is then executed in a new execution frame (see section \"Code blocks, execution frames, and name spaces\" on page 23 (ref-6.html#MARKER-9-3)), using a newly created local name space and the original global name space. (Usually, the suite contains only function definitions.) When the class's suite finishes execution, its execution frame is discarded but its local name space is saved. A class object is then created using the inheritance list for the base classes and the saved local name space for the attribute dictionary. The class name is bound to this class object in the original local name space.\nProgrammer's note: variables defined in the class definition are class variables; they are shared by all instances. To define instance variables, they must be given a value in the the `__init__` method or in another method. Both class and instance variables are accessible through the notation \"`self.name`\", and an instance variable hides a class variable with the same name when accessed in this way. Class variables with immutable values can be used as defaults for instance variables.\n---\n[6] Currently this is not checked; instead, def f(a=1,b) is interpreted as def f(a=1,b=None).\nTOC\n---\nPython 1.5 Reference Manual - 13 JAN 1998\n[Next] (ref-10.html)[Previous] (ref-8.html)[Top] (ref-1.html)[Contents] (ref-2.html)[Index]\nGenerated with Harlequin WebMaker (http://www.harlequin.com/webmaker)", "python_version": "1.5", "length": 14993, "url": "https://docs.python.org/1.5/ref/ref-9.html"} {"title": "Footnotes", "text": "guido@python.org", "python_version": "1.5", "length": 16, "url": "https://docs.python.org/1.5/tut/footnode.html"} {"title": "Python Tutorial", "text": "node1.html\nnode1.html\n---\n# Python Tutorial\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE 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 document. The Python Reference\nManual gives a more formal definition of the language. To write\nextensions in C or C++, read the Extending and Embedding and\nPython/C API manuals. There are also several books covering\nPython 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 Reference.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Whetting Your Appetite (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 Where From Here (node4.html#SECTION002200000000000000000)\n2 Using the Python Interpreter (node5.html#SECTION003000000000000000000)\n- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)\n- Argument Passing (node7.html#SECTION003110000000000000000)\nInteractive Mode (node8.html#SECTION003120000000000000000)\n2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)\n- Error Handling (node10.html#SECTION003210000000000000000)\nExecutable Python scripts (node11.html#SECTION003220000000000000000)\nThe Interactive Startup File (node12.html#SECTION003230000000000000000)\n3 An Informal Introduction to Python (node13.html#SECTION004000000000000000000)\n- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)\n- Numbers (node15.html#SECTION004110000000000000000)\nStrings (node16.html#SECTION004120000000000000000)\nLists (node17.html#SECTION004130000000000000000)\n3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)\n4 More Control Flow Tools (node19.html#SECTION005000000000000000000)\n- 4.1 If Statements (node20.html#SECTION005100000000000000000)\n4.2 For Statements (node21.html#SECTION005200000000000000000)\n4.3 The range() Function (node22.html#SECTION005300000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)\n4.5 Pass Statements (node24.html#SECTION005500000000000000000)\n4.6 Defining Functions (node25.html#SECTION005600000000000000000)\n4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)\n- Default Argument Values (node27.html#SECTION005710000000000000000)\nKeyword Arguments (node28.html#SECTION005720000000000000000)\nArbitrary Argument Lists (node29.html#SECTION005730000000000000000)\n5 Data Structures (node30.html#SECTION006000000000000000000)\n- 5.1 More on Lists (node31.html#SECTION006100000000000000000)\n- Functional Programming Tools (node32.html#SECTION006110000000000000000)\n5.2 The del statement (node33.html#SECTION006200000000000000000)\n5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)\n5.4 Dictionaries (node35.html#SECTION006400000000000000000)\n5.5 More on Conditions (node36.html#SECTION006500000000000000000)\n5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)\n6 Modules (node38.html#SECTION007000000000000000000)\n- 6.1 More on Modules (node39.html#SECTION007100000000000000000)\n- The Module Search Path (node40.html#SECTION007110000000000000000)\n``Compiled'' Python files (node41.html#SECTION007120000000000000000)\n6.2 Standard Modules (node42.html#SECTION007200000000000000000)\n6.3 The dir() function (node43.html#SECTION007300000000000000000)\n7 Input and Output (node44.html#SECTION008000000000000000000)\n- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)\n7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)\n- Methods of file objects (node47.html#SECTION008210000000000000000)\nThe pickle module (node48.html#SECTION008220000000000000000)\n8 Errors and Exceptions (node49.html#SECTION009000000000000000000)\n- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)\n8.2 Exceptions (node51.html#SECTION009200000000000000000)\n8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)\n8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)\n8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)\n8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)\n9 Classes (node56.html#SECTION0010000000000000000000)\n- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)\n9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)\n9.3 A first look at classes (node59.html#SECTION0010300000000000000000)\n- Class definition syntax (node60.html#SECTION0010310000000000000000)\nClass objects (node61.html#SECTION0010320000000000000000)\nInstance objects (node62.html#SECTION0010330000000000000000)\nMethod objects (node63.html#SECTION0010340000000000000000)\n9.4 Random remarks (node64.html#SECTION0010400000000000000000)\n9.5 Inheritance (node65.html#SECTION0010500000000000000000)\n- Multiple inheritance (node66.html#SECTION0010510000000000000000)\n9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)\n9.7 Odds and ends (node68.html#SECTION0010700000000000000000)\n- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)\n10 What Now? (node70.html#SECTION0011000000000000000000)\n11 Recent Additions as of Release 1.1 (node71.html#SECTION0012000000000000000000)\n- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)\n11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)\nA Interactive Input Editing and History Substitution (node74.html#SECTION0013000000000000000000)\n- A.1 Line Editing (node75.html#SECTION0013100000000000000000)\nA.2 History Substitution (node76.html#SECTION0013200000000000000000)\nA.3 Key Bindings (node77.html#SECTION0013300000000000000000)\nA.4 Commentary (node78.html#SECTION0013400000000000000000)\nAbout this document ... (node79.html#SECTION0014000000000000000000)\n---\nnode1.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 8759, "url": "https://docs.python.org/1.5/tut/index.html"} {"title": "Contents", "text": "node2.html\ntut.html\ntut.html\n---\n## Contents\n- 1 Whetting Your Appetite (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 Where From Here (node4.html#SECTION002200000000000000000)\n2 Using the Python Interpreter (node5.html#SECTION003000000000000000000)\n- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)\n- Argument Passing (node7.html#SECTION003110000000000000000)\nInteractive Mode (node8.html#SECTION003120000000000000000)\n2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)\n- Error Handling (node10.html#SECTION003210000000000000000)\nExecutable Python scripts (node11.html#SECTION003220000000000000000)\nThe Interactive Startup File (node12.html#SECTION003230000000000000000)\n3 An Informal Introduction to Python (node13.html#SECTION004000000000000000000)\n- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)\n- Numbers (node15.html#SECTION004110000000000000000)\nStrings (node16.html#SECTION004120000000000000000)\nLists (node17.html#SECTION004130000000000000000)\n3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)\n4 More Control Flow Tools (node19.html#SECTION005000000000000000000)\n- 4.1 If Statements (node20.html#SECTION005100000000000000000)\n4.2 For Statements (node21.html#SECTION005200000000000000000)\n4.3 The range() Function (node22.html#SECTION005300000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)\n4.5 Pass Statements (node24.html#SECTION005500000000000000000)\n4.6 Defining Functions (node25.html#SECTION005600000000000000000)\n4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)\n- Default Argument Values (node27.html#SECTION005710000000000000000)\nKeyword Arguments (node28.html#SECTION005720000000000000000)\nArbitrary Argument Lists (node29.html#SECTION005730000000000000000)\n5 Data Structures (node30.html#SECTION006000000000000000000)\n- 5.1 More on Lists (node31.html#SECTION006100000000000000000)\n- Functional Programming Tools (node32.html#SECTION006110000000000000000)\n5.2 The del statement (node33.html#SECTION006200000000000000000)\n5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)\n5.4 Dictionaries (node35.html#SECTION006400000000000000000)\n5.5 More on Conditions (node36.html#SECTION006500000000000000000)\n5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)\n6 Modules (node38.html#SECTION007000000000000000000)\n- 6.1 More on Modules (node39.html#SECTION007100000000000000000)\n- The Module Search Path (node40.html#SECTION007110000000000000000)\n``Compiled'' Python files (node41.html#SECTION007120000000000000000)\n6.2 Standard Modules (node42.html#SECTION007200000000000000000)\n6.3 The dir() function (node43.html#SECTION007300000000000000000)\n7 Input and Output (node44.html#SECTION008000000000000000000)\n- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)\n7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)\n- Methods of file objects (node47.html#SECTION008210000000000000000)\nThe pickle module (node48.html#SECTION008220000000000000000)\n8 Errors and Exceptions (node49.html#SECTION009000000000000000000)\n- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)\n8.2 Exceptions (node51.html#SECTION009200000000000000000)\n8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)\n8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)\n8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)\n8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)\n9 Classes (node56.html#SECTION0010000000000000000000)\n- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)\n9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)\n9.3 A first look at classes (node59.html#SECTION0010300000000000000000)\n- Class definition syntax (node60.html#SECTION0010310000000000000000)\nClass objects (node61.html#SECTION0010320000000000000000)\nInstance objects (node62.html#SECTION0010330000000000000000)\nMethod objects (node63.html#SECTION0010340000000000000000)\n9.4 Random remarks (node64.html#SECTION0010400000000000000000)\n9.5 Inheritance (node65.html#SECTION0010500000000000000000)\n- Multiple inheritance (node66.html#SECTION0010510000000000000000)\n9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)\n9.7 Odds and ends (node68.html#SECTION0010700000000000000000)\n- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)\n10 What Now? (node70.html#SECTION0011000000000000000000)\n11 Recent Additions as of Release 1.1 (node71.html#SECTION0012000000000000000000)\n- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)\n11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)\nA Interactive Input Editing and History Substitution (node74.html#SECTION0013000000000000000000)\n- A.1 Line Editing (node75.html#SECTION0013100000000000000000)\nA.2 History Substitution (node76.html#SECTION0013200000000000000000)\nA.3 Key Bindings (node77.html#SECTION0013300000000000000000)\nA.4 Commentary (node78.html#SECTION0013400000000000000000)\nAbout this document ... (node79.html#SECTION0014000000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 5323, "url": "https://docs.python.org/1.5/tut/node1.html"} {"title": "Error Handling", "text": "node11.html\nnode9.html\nnode9.html\nnode1.html\n---\n## Error Handling\nWhen an error occurs, the interpreter prints an error\nmessage and a stack trace. In interactive mode, it then returns to\nthe primary prompt; when input came from a file, it exits with a\nnonzero exit status after printing\nthe stack trace. (Exceptions handled by an except clause in a\ntry statement are not errors in this context.) Some errors are\nunconditionally fatal and cause an exit with a nonzero exit; this\napplies to internal inconsistencies and some cases of running out of\nmemory. All error messages are written to the standard error stream;\nnormal output from the executed commands is written to standard\noutput.\nTyping the interrupt character (usually Control-C or DEL) to the\nprimary or secondary prompt cancels the input and returns to the\nprimary prompt.footnode.html#91\nTyping an interrupt while a command is executing raises the\nKeyboardInterrupt exception, which may be handled by a\ntry statement.\n---\nguido@python.org", "python_version": "1.5", "length": 1001, "url": "https://docs.python.org/1.5/tut/node10.html"} {"title": "Executable Python scripts", "text": "node12.html\nnode9.html\nnode10.html\nnode1.html\n---\n## 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#! /usr/bin/env python\n```\n(assuming that the interpreter is on the user's PATH) at the beginning\nof the script and giving the file an executable mode. The `#!'\nmust be the first two characters of the file.\n---\nguido@python.org", "python_version": "1.5", "length": 427, "url": "https://docs.python.org/1.5/tut/node11.html"} {"title": "The Interactive Startup File", "text": "node13.html\nnode9.html\nnode11.html\nnode1.html\n---\n## The Interactive Startup File\nWhen you use Python interactively, it is frequently handy to have some\nstandard commands executed every time the interpreter is started. You\ncan do this by setting an environment variable named\nPYTHONSTARTUP to the name of a file containing your start-up\ncommands. This is similar to the `.profile' feature of the Unix\nshells.\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, e.g.\n`execfile('.pythonrc')'. If you want to use the startup file\nin a script, you must write this explicitly in the script:\n```text\nimport os\nexecfile(os.environ['PYTHONSTARTUP'])\n```\n---\nguido@python.org", "python_version": "1.5", "length": 1207, "url": "https://docs.python.org/1.5/tut/node12.html"} {"title": "3 An Informal Introduction to Python", "text": "node14.html\ntut.html\nnode12.html\nnode1.html\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.\n---\n- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)\n- Numbers (node15.html#SECTION004110000000000000000)\nStrings (node16.html#SECTION004120000000000000000)\nLists (node17.html#SECTION004130000000000000000)\n3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 842, "url": "https://docs.python.org/1.5/tut/node13.html"} {"title": "3.1 Using Python as a Calculator", "text": "node15.html\nnode13.html\nnode13.html\nnode1.html\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---\n- Numbers (node15.html#SECTION004110000000000000000)\nStrings (node16.html#SECTION004120000000000000000)\nLists (node17.html#SECTION004130000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 391, "url": "https://docs.python.org/1.5/tut/node14.html"} {"title": "Numbers", "text": "node16.html\nnode14.html\nnode14.html\nnode1.html\n---\n## 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 /\nwork just like in most other languages (e.g., Pascal or C); parentheses\ncan be used for grouping. For example:\n```text\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>>> width = 20\n>>> height = 5*9\n>>> width * height\n900\n```\nA value can be assigned to several variables simultaneously:\n```text\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>>> 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>>> 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>>> 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>>> 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>>> 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---\nguido@python.org", "python_version": "1.5", "length": 2642, "url": "https://docs.python.org/1.5/tut/node15.html"} {"title": "Strings", "text": "node17.html\nnode14.html\nnode15.html\nnode1.html\n---\n## 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>>> '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\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\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\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\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 +\noperator, and repeated with *:\n```text\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 expressions.\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>>> word[4]\n'A'\n>>> word[0:2]\n'He'\n>>> word[2:4]\n'lp'\n```\nSlice indices have useful defaults; an omitted first index defaults to\nzero, an omitted second index defaults to the size of the string being\nsliced.\n```text\n>>> 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: s[:i] + s[i:]\nequals s.\n```text\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>>> 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>>> 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>>> 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>>> 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| 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 nonnegative indices, the length of a slice is the difference of\nthe indices, if both are within bounds, e.g., the length of\nword[1:3] is 2.\nThe built-in function len() returns the length of a string:\n```text\n>>> s = 'supercalifragilisticexpialidocious'\n>>> len(s)\n34\n```\n---\nnode17.html\nnode14.html\nnode15.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4818, "url": "https://docs.python.org/1.5/tut/node16.html"} {"title": "Lists", "text": "node18.html\nnode14.html\nnode16.html\nnode1.html\n---\n## 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>>> 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>>> 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>>> 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>>> # 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>>> len(a)\n8\n```\nIt is possible to nest lists (create lists containing other lists),\nfor example:\n```text\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---\nguido@python.org", "python_version": "1.5", "length": 1826, "url": "https://docs.python.org/1.5/tut/node17.html"} {"title": "3.2 First Steps Towards Programming", "text": "node19.html\nnode13.html\nnode17.html\nnode1.html\n---\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>>> # 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\na 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 while loop executes as long as the condition (here:\nb < 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: <, >, ==, <=,\n>= and !=.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).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>>> 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>>> 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.\n---\nnode19.html\nnode13.html\nnode17.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2515, "url": "https://docs.python.org/1.5/tut/node18.html"} {"title": "4 More Control Flow Tools", "text": "node20.html\ntut.html\nnode18.html\nnode1.html\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---\n- 4.1 If Statements (node20.html#SECTION005100000000000000000)\n4.2 For Statements (node21.html#SECTION005200000000000000000)\n4.3 The range() Function (node22.html#SECTION005300000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)\n4.5 Pass Statements (node24.html#SECTION005500000000000000000)\n4.6 Defining Functions (node25.html#SECTION005600000000000000000)\n4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)\n- Default Argument Values (node27.html#SECTION005710000000000000000)\nKeyword Arguments (node28.html#SECTION005720000000000000000)\nArbitrary Argument Lists (node29.html#SECTION005730000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 936, "url": "https://docs.python.org/1.5/tut/node19.html"} {"title": "1 Whetting Your Appetite", "text": "node3.html\ntut.html\nnode1.html\nnode1.html\n---\n# 1 Whetting Your Appetite\n---\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 Where From Here (node4.html#SECTION002200000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 220, "url": "https://docs.python.org/1.5/tut/node2.html"} {"title": "4.1 If Statements", "text": "node21.html\nnode19.html\nnode19.html\nnode1.html\n---\n# 4.1 If Statements\nPerhaps the most well-known statement type is the if\nstatement. For example:\n```text\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 else\npart is optional. The keyword `elif' is short for `else\nif', and is useful to avoid excessive indentation. An\nif ... elif ... elif\n... sequence is a substitute for the switch or\ncase statements found in other languages.\n---\nguido@python.org", "python_version": "1.5", "length": 613, "url": "https://docs.python.org/1.5/tut/node20.html"} {"title": "4.2 For Statements", "text": "node22.html\nnode19.html\nnode20.html\nnode1.html\n---\n# 4.2 For Statements\nThe for statement in Python differs a bit from what you may be\nused to in C or Pascal. Rather than always iterating over an\narithmetic progression of numbers (like in Pascal), or leaving the user\ncompletely free in the iteration test and step (as C), Python's\nfor statement iterates over the items of any sequence (e.g., a\nlist or a string), in the order that they appear in the sequence. For\nexample (no pun intended):\n```text\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>>> 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---\nguido@python.org", "python_version": "1.5", "length": 1135, "url": "https://docs.python.org/1.5/tut/node21.html"} {"title": "4.3 The range() Function", "text": "node23.html\nnode19.html\nnode21.html\nnode1.html\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>>> 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;\nrange(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):\n```text\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 range()\nand len() as follows:\n```text\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---\nguido@python.org", "python_version": "1.5", "length": 931, "url": "https://docs.python.org/1.5/tut/node22.html"} {"title": "4.4 Break and Continue Statements, and Else Clauses on Loops", "text": "node24.html\nnode19.html\nnode22.html\nnode1.html\n---\n# 4.4 Break and Continue Statements, and Else 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>>> 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---\nguido@python.org", "python_version": "1.5", "length": 939, "url": "https://docs.python.org/1.5/tut/node23.html"} {"title": "4.5 Pass Statements", "text": "node25.html\nnode19.html\nnode23.html\nnode1.html\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>>> while 1:\n... pass # Busy-wait for keyboard interrupt\n...\n```\n---\nguido@python.org", "python_version": "1.5", "length": 306, "url": "https://docs.python.org/1.5/tut/node24.html"} {"title": "4.6 Defining Functions", "text": "node26.html\nnode19.html\nnode24.html\nnode1.html\n---\n# 4.6 Defining Functions\nWe can create a function that writes the Fibonacci series to an\narbitrary boundary:\n```text\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, indented by a tab stop. The first statement\nof the function body can optionally be a string literal; this string\nliteral is the function's documentation string, or docstring.\nThere are tools which use docstrings to automatically produce printed\ndocumentation, or to let the user interactively browse through code;\nit's good practice to include docstrings in code that you write, so\ntry 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.footnode.html#701\nWhen 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>>> 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>>> 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>>> 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.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---\nnode26.html\nnode19.html\nnode24.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4265, "url": "https://docs.python.org/1.5/tut/node25.html"} {"title": "4.7 More on Defining Functions", "text": "node27.html\nnode19.html\nnode25.html\nnode1.html\n---\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---\n- Default Argument Values (node27.html#SECTION005710000000000000000)\nKeyword Arguments (node28.html#SECTION005720000000000000000)\nArbitrary Argument Lists (node29.html#SECTION005730000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 429, "url": "https://docs.python.org/1.5/tut/node26.html"} {"title": "Default Argument Values", "text": "node28.html\nnode26.html\nnode26.html\nnode1.html\n---\n## 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\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:\nask_ok('Do you really want to quit?') or like this:\nask_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\ni = 5\ndef f(arg = i): print arg\ni = 6\nf()\n```\nwill print 5.\n---\nguido@python.org", "python_version": "1.5", "length": 853, "url": "https://docs.python.org/1.5/tut/node27.html"} {"title": "Keyword Arguments", "text": "node29.html\nnode26.html\nnode27.html\nnode1.html\n---\n## Keyword Arguments\nFunctions can also be called using\nkeyword arguments of the form `keyword = value'. For\ninstance, the following function:\n```text\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\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\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 must receive a\nvalue more than once -- formal parameter names corresponding to\npositional arguments cannot be used as keywords in the same calls.\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 *name\n(described in the next subsection) which receives a tuple containing\nthe positional arguments beyond the formal parameter list.\n(*name must occur before **name.) For\nexample, if we define a function like this:\n```text\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\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-- 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---\nguido@python.org", "python_version": "1.5", "length": 2524, "url": "https://docs.python.org/1.5/tut/node28.html"} {"title": "Arbitrary Argument Lists", "text": "node30.html\nnode26.html\nnode28.html\nnode1.html\n---\n## 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\ndef fprintf(file, format, *args):\nfile.write(format % args)\n```\n---\nguido@python.org", "python_version": "1.5", "length": 425, "url": "https://docs.python.org/1.5/tut/node29.html"} {"title": "1.1 Introduction", "text": "node4.html\nnode2.html\nnode2.html\nnode1.html\n---\n# 1.1 Introduction\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\nprograms, for several reasons:\n- the high-level data types allow you to express complex operations in a\nsingle statement;statement grouping is done by indentation instead of begin/end\nbrackets;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---\nnode4.html\nnode2.html\nnode2.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3548, "url": "https://docs.python.org/1.5/tut/node3.html"} {"title": "5 Data Structures", "text": "node31.html\ntut.html\nnode29.html\nnode1.html\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---\n- 5.1 More on Lists (node31.html#SECTION006100000000000000000)\n- Functional Programming Tools (node32.html#SECTION006110000000000000000)\n5.2 The del statement (node33.html#SECTION006200000000000000000)\n5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)\n5.4 Dictionaries (node35.html#SECTION006400000000000000000)\n5.5 More on Conditions (node36.html#SECTION006500000000000000000)\n5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 685, "url": "https://docs.python.org/1.5/tut/node30.html"} {"title": "5.1 More on Lists", "text": "node32.html\nnode30.html\nnode30.html\nnode1.html\n---\n# 5.1 More on Lists\nThe list data type has some more methods. Here are all of the methods\nof list objects:\nAn example that uses all list methods:\n```text\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---\n- Functional Programming Tools (node32.html#SECTION006110000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 662, "url": "https://docs.python.org/1.5/tut/node31.html"} {"title": "Functional Programming Tools", "text": "node33.html\nnode31.html\nnode31.html\nnode1.html\n---\n## 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>>> 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\nfunction(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>>> 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>>> 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>>> 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>>> 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---\nguido@python.org", "python_version": "1.5", "length": 2282, "url": "https://docs.python.org/1.5/tut/node32.html"} {"title": "5.2 The del statement", "text": "node34.html\nnode30.html\nnode32.html\nnode1.html\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>>> 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>>> 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 del\nlater.\n---\nguido@python.org", "python_version": "1.5", "length": 668, "url": "https://docs.python.org/1.5/tut/node33.html"} {"title": "5.3 Tuples and Sequences", "text": "node35.html\nnode30.html\nnode33.html\nnode1.html\n---\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>>> 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>>> 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>>> x, y, z = t\n```\nThis is called, appropriately enough, tuple unpacking. Tuple\nunpacking requires that the list of variables on the left has 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>>> a = ['spam', 'eggs', 100, 1234]\n>>> [a1, a2, a3, a4] = a\n```\n---\nnode35.html\nnode30.html\nnode33.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2458, "url": "https://docs.python.org/1.5/tut/node34.html"} {"title": "5.4 Dictionaries", "text": "node36.html\nnode30.html\nnode34.html\nnode1.html\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 non-mutable 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 the\nkeys used in the dictionary, in random order (if you want it sorted,\njust apply the sort() method to the list of keys). To check\nwhether a single key is in the dictionary, use the has_key()\nmethod of the dictionary.\nHere is a small example using a dictionary:\n```text\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---\nguido@python.org", "python_version": "1.5", "length": 1933, "url": "https://docs.python.org/1.5/tut/node35.html"} {"title": "5.5 More on Conditions", "text": "node37.html\nnode30.html\nnode35.html\nnode1.html\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\nis 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 a\nis less than b and moreover b equals c.\nComparisons may be combined by the Boolean operators and and\nor, 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\nA 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>>> 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.\n---\nguido@python.org", "python_version": "1.5", "length": 1790, "url": "https://docs.python.org/1.5/tut/node36.html"} {"title": "5.6 Comparing Sequences and Other Types", "text": "node38.html\nnode30.html\nnode36.html\nnode1.html\n---\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(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.footnode.html#348\n---\nguido@python.org", "python_version": "1.5", "length": 1453, "url": "https://docs.python.org/1.5/tut/node37.html"} {"title": "6 Modules", "text": "node39.html\ntut.html\nnode37.html\nnode1.html\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# 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>>> import fibo\n```\nThis does not enter the names of the functions defined in\nfibo\ndirectly in the current symbol table; it only enters the module name\nfibo\nthere.\nUsing the module name you can access the functions:\n```text\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>>> fib = fibo.fib\n>>> fib(500)\n1 1 2 3 5 8 13 21 34 55 89 144 233 377\n```\n---\n- 6.1 More on Modules (node39.html#SECTION007100000000000000000)\n- The Module Search Path (node40.html#SECTION007110000000000000000)\n``Compiled'' Python files (node41.html#SECTION007120000000000000000)\n6.2 Standard Modules (node42.html#SECTION007200000000000000000)\n6.3 The dir() function (node43.html#SECTION007300000000000000000)\n---\nnode39.html\ntut.html\nnode37.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2667, "url": "https://docs.python.org/1.5/tut/node38.html"} {"title": "6.1 More on Modules", "text": "node40.html\nnode38.html\nnode38.html\nnode1.html\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\ntime the module is imported somewhere.footnode.html#361\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,\nmodname.itemname.\nModules can import other modules.\nIt is customary but not required to place all\nimport\nstatements at the beginning of a module (or script, for that matter).\nThe imported module names are placed in the importing module's global\nsymbol table.\nThere is a variant of the\nimport\nstatement that imports names from a module directly into the importing\nmodule's symbol table.\nFor example:\n```text\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>>> 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---\n- The Module Search Path (node40.html#SECTION007110000000000000000)\n``Compiled'' Python files (node41.html#SECTION007120000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1730, "url": "https://docs.python.org/1.5/tut/node39.html"} {"title": "1.2 Where From Here", "text": "node5.html\nnode2.html\nnode3.html\nnode1.html\n---\n# 1.2 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 though 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.\n---\nguido@python.org", "python_version": "1.5", "length": 712, "url": "https://docs.python.org/1.5/tut/node4.html"} {"title": "The Module Search Path", "text": "node41.html\nnode39.html\nnode39.html\nnode1.html\n---\n## 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 Unix shell variable PATH, i.e., a list of colon-separated\ndirectory names. When PYTHONPATH is not set, or when the file\nis not found there, the search continues in an installation-dependent\ndefault path, usually `.:/usr/local/lib/python'.\nActually, modules are searched in the list of directories given by the\nvariable sys.path which is initialized from the directory\ncontaining the input script (or the current directory),\nPYTHONPATH and the installation-dependent default. This allows\nPython programs that know what they're doing to modify or replace the\nmodule search path. See the section on Standard Modules later.\n---\nguido@python.org", "python_version": "1.5", "length": 951, "url": "https://docs.python.org/1.5/tut/node40.html"} {"title": "``Compiled'' Python files", "text": "node42.html\nnode39.html\nnode40.html\nnode1.html\n---\n## ``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-``compiled'' version of the module spam.\nThe modification time of the version of `spam.py' used to create\n`spam.pyc' is recorded in `spam.pyc', and the file is\nignored if these don't match.\nNormally, you don't need to do anything to create the `spam.pyc' file.\nWhenever `spam.py' is successfully compiled, an attempt is made to\nwrite the compiled version to `spam.pyc'. It is not an error if\nthis attempt fails; if for any reason the file is not written\ncompletely, the resulting `spam.pyc' file will be recognized as\ninvalid and thus ignored later. The contents of the `spam.pyc'\nfile is platform independent, so a Python module directory can be\nshared by machines of different architectures. (Tip for experts:\nthe module compileall creates file.pyc files for all\nmodules.)\n---\nguido@python.org", "python_version": "1.5", "length": 1092, "url": "https://docs.python.org/1.5/tut/node41.html"} {"title": "6.2 Standard Modules", "text": "node43.html\nnode38.html\nnode41.html\nnode1.html\n---\n# 6.2 Standard Modules\nPython comes with a library of standard modules, described in a separate\ndocument, the Python Library Reference (``Library Reference''\nhereafter). Some modules are built into the interpreter; these\nprovide access to operations that are not part of the core of the\nlanguage but are nevertheless built in, either for efficiency or to\nprovide access to operating system primitives such as system calls.\nThe set of such modules is a configuration option; e.g., the\namoeba module is only provided on systems that somehow\nsupport Amoeba primitives. One particular module deserves some\nattention: sys, which is built into every Python interpreter.\nThe variables sys.ps1 and sys.ps2 define the strings\nused as primary and secondary prompts:\n```text\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\nsys.path\nis a list of strings that determine the interpreter's search path for\nmodules.\nIt is initialized to a default path taken from the environment variable\nPYTHONPATH,\nor from a built-in default if\nPYTHONPATH\nis not set.\nYou can modify it using standard list operations, e.g.:\n```text\n>>> import sys\n>>> sys.path.append('/ufs/guido/lib/python')\n```\n---\nguido@python.org", "python_version": "1.5", "length": 1384, "url": "https://docs.python.org/1.5/tut/node42.html"} {"title": "6.3 The dir() function", "text": "node44.html\nnode38.html\nnode42.html\nnode1.html\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>>> 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>>> 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>>> 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---\nguido@python.org", "python_version": "1.5", "length": 1584, "url": "https://docs.python.org/1.5/tut/node43.html"} {"title": "7 Input and Output", "text": "node45.html\ntut.html\nnode43.html\nnode1.html\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---\n- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)\n7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)\n- Methods of file objects (node47.html#SECTION008210000000000000000)\nThe pickle module (node48.html#SECTION008220000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 566, "url": "https://docs.python.org/1.5/tut/node44.html"} {"title": "7.1 Fancier Output Formatting", "text": "node46.html\nnode44.html\nnode44.html\nnode1.html\n---\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 string contains\nsome useful operations for padding strings to a given column width;\nthese will be discussed shortly. The second way is to use the\n% operator with a string as the left argument. %\ninterprets the left argument as a C sprintf()-style\nformat string to be applied to the right argument, and returns the\nstring resulting 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>>> 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>>> 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>>> 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>>> 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>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}\n>>> for name, phone in table.items():\n... print '%-10s ==> %10d' % (name, phone)\n...\nJack ==> 4098\nDcab ==> 8637678\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>>> 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---\nnode46.html\nnode44.html\nnode44.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4835, "url": "https://docs.python.org/1.5/tut/node45.html"} {"title": "7.2 Reading and Writing Files", "text": "node47.html\nnode44.html\nnode45.html\nnode1.html\n---\n# 7.2 Reading and Writing Files\nopen() returns a file object, and is most commonly used with\ntwo arguments: `open(filename, mode)'.\n```text\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, (XXX does the Mac need this too?) '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.\n---\n- Methods of file objects (node47.html#SECTION008210000000000000000)\nThe pickle module (node48.html#SECTION008220000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1496, "url": "https://docs.python.org/1.5/tut/node46.html"} {"title": "Methods of file objects", "text": "node48.html\nnode46.html\nnode46.html\nnode1.html\n---\n## 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>>> f.read()\n'This is the entire file.\\012'\n>>> f.read()\n''\n```\nf.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\nf.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>>> 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```\nf.readlines() uses f.readline() repeatedly, and returns\na list containing all the lines of data in the file.\n```text\n>>> f.readlines()\n['This is the first line of the file.\\012', 'Second line of the file\\012']\n```\nf.write(string) writes the contents of string to\nthe file, returning None.\n```text\n>>> f.write('This is a test\\n')\n```\nf.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 from_what\nvalue of 0 measures from the beginning of the file, 1 uses the current\nfile position, and 2 uses the end of the file as the reference point.\nfrom_what can be omitted and defaults to 0, using the beginning\nof the file as the reference point.\n```text\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\nf.close(), attempts to use the file object will automatically fail.\n```text\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 isatty()\nand truncate() which are less frequently used; consult the\nLibrary Reference for a complete guide to file objects.\n---\nnode48.html\nnode46.html\nnode46.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2953, "url": "https://docs.python.org/1.5/tut/node47.html"} {"title": "The pickle module", "text": "node49.html\nnode46.html\nnode47.html\nnode1.html\n---\n## 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\npickle.dump(x, f)\n```\nTo unpickle the object again, if f is a file object which has\nbeen opened for reading:\n```text\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 be\nstored and reused by other programs or by a future invocation of the\nsame program; the technical term for this is a persistent\nobject. Because pickle is so widely used, many authors who\nwrite Python extensions take care to ensure that new data types such\nas matrices, XXX more examples needed XXX, can be properly pickled and\nunpickled.\n---\nnode49.html\nnode46.html\nnode47.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 1997, "url": "https://docs.python.org/1.5/tut/node48.html"} {"title": "8 Errors and Exceptions", "text": "node50.html\ntut.html\nnode48.html\nnode1.html\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: syntax errors\nand exceptions.\n---\n- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)\n8.2 Exceptions (node51.html#SECTION009200000000000000000)\n8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)\n8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)\n8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)\n8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 711, "url": "https://docs.python.org/1.5/tut/node49.html"} {"title": "2 Using the Python Interpreter", "text": "node6.html\ntut.html\nnode4.html\nnode1.html\n---\n# 2 Using the Python Interpreter\n---\n- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)\n- Argument Passing (node7.html#SECTION003110000000000000000)\nInteractive Mode (node8.html#SECTION003120000000000000000)\n2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)\n- Error Handling (node10.html#SECTION003210000000000000000)\nExecutable Python scripts (node11.html#SECTION003220000000000000000)\nThe Interactive Startup File (node12.html#SECTION003230000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 579, "url": "https://docs.python.org/1.5/tut/node5.html"} {"title": "8.1 Syntax Errors", "text": "node51.html\nnode49.html\nnode49.html\nnode1.html\n---\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>>> 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 detected.\nThe error is caused by (or at least detected at) the token\npreceding\nthe arrow: in the example, the error is detected at the keyword\nprint, since a colon (:) is missing before it.\nFile name and line number are printed so you know where to look in case\nthe input came from a script.\n---\nguido@python.org", "python_version": "1.5", "length": 775, "url": "https://docs.python.org/1.5/tut/node50.html"} {"title": "8.2 Exceptions", "text": "node52.html\nnode49.html\nnode50.html\nnode1.html\n---\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>>> 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,\nNameError\nand\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 Library Reference lists the built-in exceptions and their\nmeanings.\n---\nguido@python.org", "python_version": "1.5", "length": 1760, "url": "https://docs.python.org/1.5/tut/node51.html"} {"title": "8.3 Handling Exceptions", "text": "node53.html\nnode49.html\nnode51.html\nnode1.html\n---\n# 8.3 Handling Exceptions\nIt is possible to write programs that handle selected exceptions.\nLook at the following example, which prints a table of inverses of\nsome floating point numbers:\n```text\n>>> numbers = [0.3333, 2.5, 0, 10]\n>>> for x in numbers:\n... print x,\n... try:\n... print 1.0 / x\n... except ZeroDivisionError:\n... print '*** has no inverse ***'\n...\n0.3333 3.00030003\n2.5 0.4\n0 *** has no inverse ***\n10 0.1\n```\nThe try statement works as follows.\n- First, the try clause\n(the statement(s) between the try and except\nkeywords) is executed.If no exception occurs, the\nexcept clause\nis skipped and execution of the try statement is finished.If an exception occurs during execution of the try clause,\nthe rest of the clause is skipped. Then if its type matches the\nexception named after the except keyword, the rest of the\ntry clause is skipped, the except clause is executed, and then\nexecution continues after the try statement.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\nand execution stops with a message as shown above.\nA try statement may have more than one except clause, to\nspecify handlers for different exceptions.\nAt most one handler will be executed.\nHandlers only handle exceptions that occur in the corresponding try\nclause, not in other handlers of the same try statement.\nAn except clause may name multiple exceptions as a parenthesized list,\ne.g.:\n```text\n... except (RuntimeError, TypeError, NameError):\n... pass\n```\nThe last except clause may omit the exception name(s), to serve as a\nwildcard.\nUse this with extreme caution, since it is easy to mask a real\nprogramming error in this way!\nThe try ... except statement has an optional\nelse clause, which must follow all except clauses. It is\nuseful to place code that must be executed if the try clause does not\nraise an exception. For example:\n```text\nfor arg in sys.argv:\ntry:\nf = open(arg, 'r')\nexcept IOError:\nprint 'cannot open', arg\nelse:\nprint arg, 'has', len(f.readlines()), 'lines'\nf.close()\n```\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>>> 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>>> 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---\nnode53.html\nnode49.html\nnode51.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 3213, "url": "https://docs.python.org/1.5/tut/node52.html"} {"title": "8.4 Raising Exceptions", "text": "node54.html\nnode49.html\nnode52.html\nnode1.html\n---\n# 8.4 Raising Exceptions\nThe raise statement allows the programmer to force a\nspecified exception to occur.\nFor example:\n```text\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---\nguido@python.org", "python_version": "1.5", "length": 432, "url": "https://docs.python.org/1.5/tut/node53.html"} {"title": "8.5 User-defined Exceptions", "text": "node55.html\nnode49.html\nnode53.html\nnode1.html\n---\n# 8.5 User-defined Exceptions\nPrograms may name their own exceptions by assigning a string to a\nvariable.\nFor example:\n```text\n>>> my_exc = 'my_exc'\n>>> try:\n... raise my_exc, 2*2\n... except my_exc, val:\n... print 'My exception occurred, value:', val\n...\nMy exception occurred, value: 4\n>>> raise my_exc, 1\nTraceback (innermost last):\nFile \"\", line 1\nmy_exc: 1\n```\nMany standard modules use this to report errors that may occur in\nfunctions they define.\n---\nguido@python.org", "python_version": "1.5", "length": 532, "url": "https://docs.python.org/1.5/tut/node54.html"} {"title": "8.6 Defining Clean-up Actions", "text": "node56.html\nnode49.html\nnode54.html\nnode1.html\n---\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>>> 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.\n---\nguido@python.org", "python_version": "1.5", "length": 824, "url": "https://docs.python.org/1.5/tut/node55.html"} {"title": "9 Classes", "text": "node57.html\ntut.html\nnode55.html\nnode1.html\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(es), 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 C++\nor 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 members.\n---\n- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)\n9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)\n9.3 A first look at classes (node59.html#SECTION0010300000000000000000)\n- Class definition syntax (node60.html#SECTION0010310000000000000000)\nClass objects (node61.html#SECTION0010320000000000000000)\nInstance objects (node62.html#SECTION0010330000000000000000)\nMethod objects (node63.html#SECTION0010340000000000000000)\n9.4 Random remarks (node64.html#SECTION0010400000000000000000)\n9.5 Inheritance (node65.html#SECTION0010500000000000000000)\n- Multiple inheritance (node66.html#SECTION0010510000000000000000)\n9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)\n9.7 Odds and ends (node68.html#SECTION0010700000000000000000)\n- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 2490, "url": "https://docs.python.org/1.5/tut/node56.html"} {"title": "9.1 A word about terminology", "text": "node58.html\nnode56.html\nnode56.html\nnode1.html\n---\n# 9.1 A word about terminology\nLacking universally accepted terminology to talk about classes, I'll\nmake occasional use of Smalltalk and C++ terms. (I'd 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 aren't, 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---\nguido@python.org", "python_version": "1.5", "length": 1732, "url": "https://docs.python.org/1.5/tut/node57.html"} {"title": "9.2 Python scopes and name spaces", "text": "node59.html\nnode56.html\nnode57.html\nnode1.html\n---\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\nmodname.funcname, modname is a module object and\nfuncname 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 space!footnode.html#719\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 referenced by the\nlocal scope. In fact, all operations that introduce new names use the\nlocal scope: in particular, import statements and function definitions\nbind the module or function name in the local scope. (The\nglobal statement can be used to indicate that particular\nvariables live in the global scope.)\n---\nnode59.html\nnode56.html\nnode57.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4979, "url": "https://docs.python.org/1.5/tut/node58.html"} {"title": "9.3 A first look at classes", "text": "node60.html\nnode56.html\nnode58.html\nnode1.html\n---\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---\n- Class definition syntax (node60.html#SECTION0010310000000000000000)\nClass objects (node61.html#SECTION0010320000000000000000)\nInstance objects (node62.html#SECTION0010330000000000000000)\nMethod objects (node63.html#SECTION0010340000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 447, "url": "https://docs.python.org/1.5/tut/node59.html"} {"title": "2.1 Invoking the Interpreter", "text": "node7.html\nnode5.html\nnode5.html\nnode1.html\n---\n# 2.1 Invoking the Interpreter\nThe Python interpreter is usually installed as `/usr/local/bin/python'\non those machines where it is available; putting `/usr/local/bin' in\nyour Unix shell's search path makes it possible to start it by\ntyping the command\n```text\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 or F6 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 or other\ncharacters 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 \n.\n.\n.\n\n```\nClass definitions, like function definitions (def\nstatements) must be executed before they have any effect. (You could\nconceivably place a class definition in a branch of an if\nstatement, 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 class name given in\nthe class definition header (ClassName in the example).\n---\nguido@python.org", "python_version": "1.5", "length": 1481, "url": "https://docs.python.org/1.5/tut/node60.html"} {"title": "Class objects", "text": "node62.html\nnode59.html\nnode60.html\nnode1.html\n---\n## 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\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 function 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 that's read-only, returning the docstring belonging to\nthe class: \"A simple 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\nx = MyClass()\n```\ncreates a new instance of the class and assigns this object to\nthe local variable x.\n---\nguido@python.org", "python_version": "1.5", "length": 1170, "url": "https://docs.python.org/1.5/tut/node61.html"} {"title": "Instance objects", "text": "node63.html\nnode59.html\nnode61.html\nnode1.html\n---\n## 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\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\nMyClass.f is a function, but x.i is not, since\nMyClass.i is not. But x.f is not the same thing as\nMyClass.f -- it is a method object, not a function\nobject.\n---\nguido@python.org", "python_version": "1.5", "length": 1609, "url": "https://docs.python.org/1.5/tut/node62.html"} {"title": "Method objects", "text": "node64.html\nnode59.html\nnode62.html\nnode1.html\n---\n## Method objects\nUsually, a method is called immediately, e.g.:\n```text\nx.f()\n```\nIn our example, this will return the string 'hello world'.\nHowever, it is not necessary to call a method right away: x.f\nis a method object, and can be stored away and called at a later\nmoment, for example:\n```text\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---\nnode64.html\nnode59.html\nnode62.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 1954, "url": "https://docs.python.org/1.5/tut/node63.html"} {"title": "9.4 Random remarks", "text": "node65.html\nnode56.html\nnode63.html\nnode1.html\n---\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\nself. This is nothing more than a convention: the name\nself 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# 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\nself argument, e.g.:\n```text\nclass Bag:\ndef empty(self):\nself.data = []\ndef add(self, x):\nself.data.append(x)\ndef addtwice(self, x):\nself.add(x)\nself.add(x)\n```\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\ndef __init__(self):\nself.empty()\n```\nWhen a class defines an __init__() method, class\ninstantiation automatically invokes __init__() for the\nnewly-created class instance. So in the Bag example, a new\nand initialized instance can be obtained by:\n```text\nx = Bag()\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>>> 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```\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---\nnode65.html\nnode56.html\nnode63.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 4519, "url": "https://docs.python.org/1.5/tut/node64.html"} {"title": "9.5 Inheritance", "text": "node66.html\nnode56.html\nnode64.html\nnode1.html\n---\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\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\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:\nDerivedClassName() 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 ``virtual functions''.)\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---\n- Multiple inheritance (node66.html#SECTION0010510000000000000000)\n---\nnode66.html\nnode56.html\nnode64.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2223, "url": "https://docs.python.org/1.5/tut/node65.html"} {"title": "Multiple inheritance", "text": "node67.html\nnode65.html\nnode65.html\nnode1.html\n---\n## Multiple inheritance\nPython supports a limited form of multiple inheritance as well. A\nclass definition with multiple base classes looks as follows:\n```text\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---\nguido@python.org", "python_version": "1.5", "length": 1628, "url": "https://docs.python.org/1.5/tut/node66.html"} {"title": "9.6 Private variables through name mangling", "text": "node68.html\nnode56.html\nnode66.html\nnode1.html\n---\n# 9.6 Private variables through name mangling\nThere is now 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\nevalfile() does not consider the classname of the invoking\nclass to be the current class; this is similar to the effect of the\nglobal statement, the effect of which is likewise restricted to\ncode that is byte-compiled together. The same restriction applies to\ngetattr(), 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\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---\nnode68.html\nnode56.html\nnode66.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2402, "url": "https://docs.python.org/1.5/tut/node67.html"} {"title": "9.7 Odds and ends", "text": "node69.html\nnode56.html\nnode67.html\nnode1.html\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\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. (Unfortunately, this\ntechnique has its limitations: a class can't define operations that\nare accessed by special syntax such as sequence subscripting or\narithmetic operators, and assigning such a ``pseudo-file'' to\nsys.stdin will not cause the interpreter to read further input\nfrom it.)\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---\n- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 1368, "url": "https://docs.python.org/1.5/tut/node68.html"} {"title": "Exceptions Can Be Classes", "text": "node70.html\nnode68.html\nnode68.html\nnode1.html\n---\n## 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\nraise Class, instance\n\nraise instance\n```\nIn the first form, instance must be an instance of Class\nor of a class derived from it. The second form is a shorthand for\n```text\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\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 `except B'\nfirst), it would have printed B, B, B -- the first matching except\nclause 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().\nIn this release, the built-in exceptions are still strings.\n---\nguido@python.org", "python_version": "1.5", "length": 1513, "url": "https://docs.python.org/1.5/tut/node69.html"} {"title": "Argument Passing", "text": "node8.html\nnode6.html\nnode6.html\nnode1.html\n---\n## Argument Passing\nWhen known to the interpreter, the script name and additional\narguments thereafter are passed to the script in the variable\nsys.argv, which is a list of strings. Its length is at least\none; when no script and no arguments are given, sys.argv[0] is\nan empty string. When the script name is given as '-' (meaning\nstandard input), sys.argv[0] is set to '-'. When -c\ncommand is used, sys.argv[0] is set to '-c'. Options\nfound after -c command are not consumed by the Python\ninterpreter's option processing but left in sys.argv for the\ncommand to handle.\n---\nguido@python.org", "python_version": "1.5", "length": 638, "url": "https://docs.python.org/1.5/tut/node7.html"} {"title": "10 What Now?", "text": "node71.html\ntut.html\nnode69.html\nnode1.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. www.python.org 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.skyport.net, which contains a\nbunch of Python-related personal home pages; many people have\ndownloadable software here.\nFor Python-related questions and problem reports, you can post to the\nnewsgroup comp.lang.python, or send them to the mailing list at\npython-list@cwi.nl. The newsgroup and mailing list are\ngatewayed, so messages posted to one will automatically be forwarded\nto the other. There are around 20-30 postings a day, asking (and\nanswering) questions, suggesting new features, and announcing new\nmodules. But before posting, be sure to check the list of Frequently\nAsked Questions (also called the FAQ), at\nhttp://www.python.org/doc/FAQ.html, or look for it in the\n`Misc/' 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.\n---\nnode71.html\ntut.html\nnode69.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 2227, "url": "https://docs.python.org/1.5/tut/node70.html"} {"title": "11 Recent Additions as of Release 1.1", "text": "node72.html\ntut.html\nnode70.html\nnode1.html\n---\n# 11 Recent Additions as of Release 1.1\n---\n- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)\n11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 247, "url": "https://docs.python.org/1.5/tut/node71.html"} {"title": "11.1 Lambda Forms", "text": "node73.html\nnode71.html\nnode71.html\nnode1.html\n---\n# 11.1 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\ndef make_incrementor(n):\nreturn lambda x, incr=n: x+incr\n```\n---\nguido@python.org", "python_version": "1.5", "length": 815, "url": "https://docs.python.org/1.5/tut/node72.html"} {"title": "11.2 Documentation Strings", "text": "node74.html\nnode71.html\nnode72.html\nnode1.html\n---\n# 11.2 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 of more of paragraphs\ndescribing the objects calling conventions, its side effects, etc.\nSome people like to copy the Emacs convention of using UPPER CASE for\nfunction parameters -- this often saves a few words or lines.\nThe Python parser does not strip indentation from multi-line string\nliterals in Python, so tools that process documentation have to strip\nindentation. This is done using the following convention. The first\nnon-blank line after the first line of the string determines the\namount of indentation for the entire documentation string. (We can't\nuse the first line since it is generally adjacent to the string's\nopening quotes so its indentation is not apparent in the string\nliteral.) Whitespace ``equivalent'' to this indentation is then\nstripped from the start of all lines of the string. Lines that are\nindented less should not occur, but if they occur all their leading\nwhitespace should be stripped. Equivalence of whitespace should be\ntested after expansion of tabs (to 8 spaces, normally).\n---\nguido@python.org", "python_version": "1.5", "length": 1728, "url": "https://docs.python.org/1.5/tut/node73.html"} {"title": "A Interactive Input Editing and History Substitution", "text": "node75.html\ntut.html\nnode73.html\nnode1.html\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.\n---\n- A.1 Line Editing (node75.html#SECTION0013100000000000000000)\nA.2 History Substitution (node76.html#SECTION0013200000000000000000)\nA.3 Key Bindings (node77.html#SECTION0013300000000000000000)\nA.4 Commentary (node78.html#SECTION0013400000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 769, "url": "https://docs.python.org/1.5/tut/node74.html"} {"title": "A.1 Line Editing", "text": "node76.html\nnode74.html\nnode74.html\nnode1.html\n---\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---\nguido@python.org", "python_version": "1.5", "length": 730, "url": "https://docs.python.org/1.5/tut/node75.html"} {"title": "A.2 History Substitution", "text": "node77.html\nnode74.html\nnode75.html\nnode1.html\n---\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---\nguido@python.org", "python_version": "1.5", "length": 623, "url": "https://docs.python.org/1.5/tut/node76.html"} {"title": "A.3 Key Bindings", "text": "node78.html\nnode74.html\nnode76.html\nnode1.html\n---\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\nkey-name: function-name\n```\nor\n```text\n\"string\": function-name\n```\nand options can be set with\n```text\nset option-name value\n```\nFor example:\n```text\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\nTAB: complete\n```\nin your `$HOME/.inputrc'. (Of course, this makes it hard to type\nindented continuation lines...)\n---\nguido@python.org", "python_version": "1.5", "length": 944, "url": "https://docs.python.org/1.5/tut/node77.html"} {"title": "A.4 Commentary", "text": "node79.html\nnode74.html\nnode77.html\nnode1.html\n---\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.\n---\nguido@python.org", "python_version": "1.5", "length": 507, "url": "https://docs.python.org/1.5/tut/node78.html"} {"title": "About this document ...", "text": "tut.html\nnode78.html\nnode1.html\n---\n# About this document ...\nPython Tutorial\nThis document was generated using the LaTeX2HTML (http://www-dsed.llnl.gov/files/programs/unix/latex2html/manual/) translator Version 96.1 (Feb 5, 1996) Copyright © 1993, 1994, 1995, 1996, Nikos Drakos (http://cbl.leeds.ac.uk/nikos/personal.html), Computer Based Learning Unit, University of Leeds.\nThe command line arguments were:\nlatex2html -address guido@python.org tut.tex.\nThe translation was initiated by Fred L. Drake on Tue Feb 17 10:28:17 EST 1998\n---\nguido@python.org", "python_version": "1.5", "length": 555, "url": "https://docs.python.org/1.5/tut/node79.html"} {"title": "Interactive Mode", "text": "node9.html\nnode6.html\nnode7.html\nnode1.html\n---\n## Interactive Mode\nWhen commands are read from a tty, the interpreter is said to be in\ninteractive mode. In this mode it prompts for the next command\nwith the primary prompt, usually three greater-than signs\n(`>>> '); for continuation lines it prompts with the\nsecondary prompt,\nby 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\npython\nPython 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5\nCopyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam\n>>>\n```\n---\nguido@python.org", "python_version": "1.5", "length": 660, "url": "https://docs.python.org/1.5/tut/node8.html"} {"title": "2.2 The Interpreter and its Environment", "text": "node10.html\nnode5.html\nnode8.html\nnode1.html\n---\n# 2.2 The Interpreter and its Environment\n---\n- Error Handling (node10.html#SECTION003210000000000000000)\nExecutable Python scripts (node11.html#SECTION003220000000000000000)\nThe Interactive Startup File (node12.html#SECTION003230000000000000000)\n---\nguido@python.org", "python_version": "1.5", "length": 316, "url": "https://docs.python.org/1.5/tut/node9.html"} {"title": "Python Tutorial", "text": "node1.html\nnode1.html\n---\n# Python Tutorial\nGuido van Rossum\nFebruary 17, 1998\nCopyright © 1991-1995 by Stichting Mathematisch Centrum,\nAmsterdam, The Netherlands.\nAll 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 names of Stichting Mathematisch\nCentrum or CWI or Corporation for National Research Initiatives or\nCNRI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\nWhile CWI is the initial source for this software, a modified version\nis made available by the Corporation for National Research Initiatives\n(CNRI) at the Internet address ftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH\nCENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL\nDAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR\nPROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER\nTORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE 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 document. The Python Reference\nManual gives a more formal definition of the language. To write\nextensions in C or C++, read the Extending and Embedding and\nPython/C API manuals. There are also several books covering\nPython 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 Reference.\n---\n- Contents (node1.html#SECTION001000000000000000000)\n1 Whetting Your Appetite (node2.html#SECTION002000000000000000000)\n- 1.1 Introduction (node3.html#SECTION002100000000000000000)\n1.2 Where From Here (node4.html#SECTION002200000000000000000)\n2 Using the Python Interpreter (node5.html#SECTION003000000000000000000)\n- 2.1 Invoking the Interpreter (node6.html#SECTION003100000000000000000)\n- Argument Passing (node7.html#SECTION003110000000000000000)\nInteractive Mode (node8.html#SECTION003120000000000000000)\n2.2 The Interpreter and its Environment (node9.html#SECTION003200000000000000000)\n- Error Handling (node10.html#SECTION003210000000000000000)\nExecutable Python scripts (node11.html#SECTION003220000000000000000)\nThe Interactive Startup File (node12.html#SECTION003230000000000000000)\n3 An Informal Introduction to Python (node13.html#SECTION004000000000000000000)\n- 3.1 Using Python as a Calculator (node14.html#SECTION004100000000000000000)\n- Numbers (node15.html#SECTION004110000000000000000)\nStrings (node16.html#SECTION004120000000000000000)\nLists (node17.html#SECTION004130000000000000000)\n3.2 First Steps Towards Programming (node18.html#SECTION004200000000000000000)\n4 More Control Flow Tools (node19.html#SECTION005000000000000000000)\n- 4.1 If Statements (node20.html#SECTION005100000000000000000)\n4.2 For Statements (node21.html#SECTION005200000000000000000)\n4.3 The range() Function (node22.html#SECTION005300000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node23.html#SECTION005400000000000000000)\n4.5 Pass Statements (node24.html#SECTION005500000000000000000)\n4.6 Defining Functions (node25.html#SECTION005600000000000000000)\n4.7 More on Defining Functions (node26.html#SECTION005700000000000000000)\n- Default Argument Values (node27.html#SECTION005710000000000000000)\nKeyword Arguments (node28.html#SECTION005720000000000000000)\nArbitrary Argument Lists (node29.html#SECTION005730000000000000000)\n5 Data Structures (node30.html#SECTION006000000000000000000)\n- 5.1 More on Lists (node31.html#SECTION006100000000000000000)\n- Functional Programming Tools (node32.html#SECTION006110000000000000000)\n5.2 The del statement (node33.html#SECTION006200000000000000000)\n5.3 Tuples and Sequences (node34.html#SECTION006300000000000000000)\n5.4 Dictionaries (node35.html#SECTION006400000000000000000)\n5.5 More on Conditions (node36.html#SECTION006500000000000000000)\n5.6 Comparing Sequences and Other Types (node37.html#SECTION006600000000000000000)\n6 Modules (node38.html#SECTION007000000000000000000)\n- 6.1 More on Modules (node39.html#SECTION007100000000000000000)\n- The Module Search Path (node40.html#SECTION007110000000000000000)\n``Compiled'' Python files (node41.html#SECTION007120000000000000000)\n6.2 Standard Modules (node42.html#SECTION007200000000000000000)\n6.3 The dir() function (node43.html#SECTION007300000000000000000)\n7 Input and Output (node44.html#SECTION008000000000000000000)\n- 7.1 Fancier Output Formatting (node45.html#SECTION008100000000000000000)\n7.2 Reading and Writing Files (node46.html#SECTION008200000000000000000)\n- Methods of file objects (node47.html#SECTION008210000000000000000)\nThe pickle module (node48.html#SECTION008220000000000000000)\n8 Errors and Exceptions (node49.html#SECTION009000000000000000000)\n- 8.1 Syntax Errors (node50.html#SECTION009100000000000000000)\n8.2 Exceptions (node51.html#SECTION009200000000000000000)\n8.3 Handling Exceptions (node52.html#SECTION009300000000000000000)\n8.4 Raising Exceptions (node53.html#SECTION009400000000000000000)\n8.5 User-defined Exceptions (node54.html#SECTION009500000000000000000)\n8.6 Defining Clean-up Actions (node55.html#SECTION009600000000000000000)\n9 Classes (node56.html#SECTION0010000000000000000000)\n- 9.1 A word about terminology (node57.html#SECTION0010100000000000000000)\n9.2 Python scopes and name spaces (node58.html#SECTION0010200000000000000000)\n9.3 A first look at classes (node59.html#SECTION0010300000000000000000)\n- Class definition syntax (node60.html#SECTION0010310000000000000000)\nClass objects (node61.html#SECTION0010320000000000000000)\nInstance objects (node62.html#SECTION0010330000000000000000)\nMethod objects (node63.html#SECTION0010340000000000000000)\n9.4 Random remarks (node64.html#SECTION0010400000000000000000)\n9.5 Inheritance (node65.html#SECTION0010500000000000000000)\n- Multiple inheritance (node66.html#SECTION0010510000000000000000)\n9.6 Private variables through name mangling (node67.html#SECTION0010600000000000000000)\n9.7 Odds and ends (node68.html#SECTION0010700000000000000000)\n- Exceptions Can Be Classes (node69.html#SECTION0010710000000000000000)\n10 What Now? (node70.html#SECTION0011000000000000000000)\n11 Recent Additions as of Release 1.1 (node71.html#SECTION0012000000000000000000)\n- 11.1 Lambda Forms (node72.html#SECTION0012100000000000000000)\n11.2 Documentation Strings (node73.html#SECTION0012200000000000000000)\nA Interactive Input Editing and History Substitution (node74.html#SECTION0013000000000000000000)\n- A.1 Line Editing (node75.html#SECTION0013100000000000000000)\nA.2 History Substitution (node76.html#SECTION0013200000000000000000)\nA.3 Key Bindings (node77.html#SECTION0013300000000000000000)\nA.4 Commentary (node78.html#SECTION0013400000000000000000)\nAbout this document ... (node79.html#SECTION0014000000000000000000)\n---\nnode1.html\nnode1.html\nguido@python.org", "python_version": "1.5", "length": 8759, "url": "https://docs.python.org/1.5/tut/tut.html"}