{"title": "Extending and Embedding the Python Interpreter", "text": "node1.html node1.html node38.html\n---\n# Extending and Embedding the Python Interpreter\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\nOctober 25, 1996\nRelease 1.4\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.\n---\n- Contents (node1.html#SECTION00100000000000000000)\nExtending Python with C or C++ code (node2.html#SECTION00200000000000000000)\n- 1.1 Introduction (node3.html#SECTION00210000000000000000)\n1.2 A Simple Example (node4.html#SECTION00220000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION00230000000000000000)\n1.4 Back to the Example (node6.html#SECTION00240000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION00250000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION00260000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION00270000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION00280000000000000000)\nThe Py_BuildValue() Function (node11.html#SECTION00290000000000000000)\n1.10 Reference Counts (node12.html#SECTION002100000000000000000)\n- 1.10.1 Introduction (node13.html#SECTION002101000000000000000)\n1.10.2 Reference Counting in Python (node14.html#SECTION002102000000000000000)\n1.10.3 Ownership Rules (node15.html#SECTION002103000000000000000)\n1.10.4 Thin Ice (node16.html#SECTION002104000000000000000)\n1.10.5 NULL Pointers (node17.html#SECTION002105000000000000000)\nWriting Extensions in C++ (node18.html#SECTION002110000000000000000)\n2 Embedding Python in another application (node19.html#SECTION00300000000000000000)\n- Embedding Python in C++ (node20.html#SECTION00310000000000000000)\n3 Dynamic Loading (node21.html#SECTION00400000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node22.html#SECTION00410000000000000000)\n- 3.1.1 Shared Libraries (node23.html#SECTION00411000000000000000)\n3.1.2 SGI IRIX 4 Dynamic Loading (node24.html#SECTION00412000000000000000)\n3.1.3 GNU Dynamic Loading (node25.html#SECTION00413000000000000000)\n3.2 Building a Dynamically Loadable Module (node26.html#SECTION00420000000000000000)\n- 3.2.1 Shared Libraries (node27.html#SECTION00421000000000000000)\n3.2.2 SGI IRIX 4 Dynamic Loading (node28.html#SECTION00422000000000000000)\n3.2.3 GNU Dynamic Loading (node29.html#SECTION00423000000000000000)\n4 Extension Reference (node30.html#SECTION00500000000000000000)\n- 4.1 Introduction (node31.html#SECTION00510000000000000000)\n- 4.1.1 Memory Management (node32.html#SECTION00511000000000000000)\n4.2 Object Protocol (node33.html#SECTION00520000000000000000)\n4.3 Number Protocol (node34.html#SECTION00530000000000000000)\n4.4 Sequence protocol (node35.html#SECTION00540000000000000000)\n4.5 Mapping protocol (node36.html#SECTION00550000000000000000)\n4.6 Constructors (node37.html#SECTION00560000000000000000)\nIndex (node38.html#SECTION00600000000000000000)\nAbout this document ... (node39.html#SECTION00700000000000000000)\n---\nnode1.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 5349, "url": "https://docs.python.org/{python_version}/ext/ext.html"} {"title": "Footnotes", "text": "guido@cnri.reston.va.us", "python_version": "1.4", "length": 23, "url": "https://docs.python.org/{python_version}/ext/footnode.html"} {"title": "Extending and Embedding the Python Interpreter", "text": "node1.html node1.html node38.html\n---\n# Extending and Embedding the Python Interpreter\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\nOctober 25, 1996\nRelease 1.4\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.\n---\n- Contents (node1.html#SECTION00100000000000000000)\nExtending Python with C or C++ code (node2.html#SECTION00200000000000000000)\n- 1.1 Introduction (node3.html#SECTION00210000000000000000)\n1.2 A Simple Example (node4.html#SECTION00220000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION00230000000000000000)\n1.4 Back to the Example (node6.html#SECTION00240000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION00250000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION00260000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION00270000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION00280000000000000000)\nThe Py_BuildValue() Function (node11.html#SECTION00290000000000000000)\n1.10 Reference Counts (node12.html#SECTION002100000000000000000)\n- 1.10.1 Introduction (node13.html#SECTION002101000000000000000)\n1.10.2 Reference Counting in Python (node14.html#SECTION002102000000000000000)\n1.10.3 Ownership Rules (node15.html#SECTION002103000000000000000)\n1.10.4 Thin Ice (node16.html#SECTION002104000000000000000)\n1.10.5 NULL Pointers (node17.html#SECTION002105000000000000000)\nWriting Extensions in C++ (node18.html#SECTION002110000000000000000)\n2 Embedding Python in another application (node19.html#SECTION00300000000000000000)\n- Embedding Python in C++ (node20.html#SECTION00310000000000000000)\n3 Dynamic Loading (node21.html#SECTION00400000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node22.html#SECTION00410000000000000000)\n- 3.1.1 Shared Libraries (node23.html#SECTION00411000000000000000)\n3.1.2 SGI IRIX 4 Dynamic Loading (node24.html#SECTION00412000000000000000)\n3.1.3 GNU Dynamic Loading (node25.html#SECTION00413000000000000000)\n3.2 Building a Dynamically Loadable Module (node26.html#SECTION00420000000000000000)\n- 3.2.1 Shared Libraries (node27.html#SECTION00421000000000000000)\n3.2.2 SGI IRIX 4 Dynamic Loading (node28.html#SECTION00422000000000000000)\n3.2.3 GNU Dynamic Loading (node29.html#SECTION00423000000000000000)\n4 Extension Reference (node30.html#SECTION00500000000000000000)\n- 4.1 Introduction (node31.html#SECTION00510000000000000000)\n- 4.1.1 Memory Management (node32.html#SECTION00511000000000000000)\n4.2 Object Protocol (node33.html#SECTION00520000000000000000)\n4.3 Number Protocol (node34.html#SECTION00530000000000000000)\n4.4 Sequence protocol (node35.html#SECTION00540000000000000000)\n4.5 Mapping protocol (node36.html#SECTION00550000000000000000)\n4.6 Constructors (node37.html#SECTION00560000000000000000)\nIndex (node38.html#SECTION00600000000000000000)\nAbout this document ... (node39.html#SECTION00700000000000000000)\n---\nnode1.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 5349, "url": "https://docs.python.org/{python_version}/ext/index.html"} {"title": "Contents", "text": "node2.html ext.html ext.html node38.html\n---\n## Contents\n- Extending Python with C or C++ code (node2.html#SECTION00200000000000000000)\n- 1.1 Introduction (node3.html#SECTION00210000000000000000)\n1.2 A Simple Example (node4.html#SECTION00220000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION00230000000000000000)\n1.4 Back to the Example (node6.html#SECTION00240000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION00250000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION00260000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION00270000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION00280000000000000000)\nThe Py_BuildValue() Function (node11.html#SECTION00290000000000000000)\n1.10 Reference Counts (node12.html#SECTION002100000000000000000)\n- 1.10.1 Introduction (node13.html#SECTION002101000000000000000)\n1.10.2 Reference Counting in Python (node14.html#SECTION002102000000000000000)\n1.10.3 Ownership Rules (node15.html#SECTION002103000000000000000)\n1.10.4 Thin Ice (node16.html#SECTION002104000000000000000)\n1.10.5 NULL Pointers (node17.html#SECTION002105000000000000000)\nWriting Extensions in C++ (node18.html#SECTION002110000000000000000)\n2 Embedding Python in another application (node19.html#SECTION00300000000000000000)\n- Embedding Python in C++ (node20.html#SECTION00310000000000000000)\n3 Dynamic Loading (node21.html#SECTION00400000000000000000)\n- 3.1 Configuring and Building the Interpreter for Dynamic Loading (node22.html#SECTION00410000000000000000)\n- 3.1.1 Shared Libraries (node23.html#SECTION00411000000000000000)\n3.1.2 SGI IRIX 4 Dynamic Loading (node24.html#SECTION00412000000000000000)\n3.1.3 GNU Dynamic Loading (node25.html#SECTION00413000000000000000)\n3.2 Building a Dynamically Loadable Module (node26.html#SECTION00420000000000000000)\n- 3.2.1 Shared Libraries (node27.html#SECTION00421000000000000000)\n3.2.2 SGI IRIX 4 Dynamic Loading (node28.html#SECTION00422000000000000000)\n3.2.3 GNU Dynamic Loading (node29.html#SECTION00423000000000000000)\n4 Extension Reference (node30.html#SECTION00500000000000000000)\n- 4.1 Introduction (node31.html#SECTION00510000000000000000)\n- 4.1.1 Memory Management (node32.html#SECTION00511000000000000000)\n4.2 Object Protocol (node33.html#SECTION00520000000000000000)\n4.3 Number Protocol (node34.html#SECTION00530000000000000000)\n4.4 Sequence protocol (node35.html#SECTION00540000000000000000)\n4.5 Mapping protocol (node36.html#SECTION00550000000000000000)\n4.6 Constructors (node37.html#SECTION00560000000000000000)\nIndex (node38.html#SECTION00600000000000000000)\nAbout this document ... (node39.html#SECTION00700000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2735, "url": "https://docs.python.org/{python_version}/ext/node1.html"} {"title": "Format Strings for PyArg_ParseTuple()", "text": "node11.html node2.html node9.html node1.html node38.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---\nnode11.html node2.html node9.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3064, "url": "https://docs.python.org/{python_version}/ext/node10.html"} {"title": "The Py_BuildValue() Function", "text": "node12.html node2.html node10.html node1.html node38.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\n`PyArg_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\n`PyExc_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---\nnode12.html node2.html node10.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2326, "url": "https://docs.python.org/{python_version}/ext/node11.html"} {"title": "1.10 Reference Counts", "text": "node13.html node2.html node11.html node1.html node38.html\n---\n# 1.10 Reference Counts\n---\n- 1.10.1 Introduction (node13.html#SECTION002101000000000000000)\n1.10.2 Reference Counting in Python (node14.html#SECTION002102000000000000000)\n1.10.3 Ownership Rules (node15.html#SECTION002103000000000000000)\n1.10.4 Thin Ice (node16.html#SECTION002104000000000000000)\n1.10.5 NULL Pointers (node17.html#SECTION002105000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 450, "url": "https://docs.python.org/{python_version}/ext/node12.html"} {"title": "1.10.1 Introduction", "text": "node14.html node12.html node12.html node1.html node38.html\n---\n## 1.10.1 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\n`malloc()` 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\n`free()`. 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 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---\nnode14.html node12.html node12.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3430, "url": "https://docs.python.org/{python_version}/ext/node13.html"} {"title": "1.10.2 Reference Counting in Python", "text": "node15.html node12.html node13.html node1.html node38.html\n---\n## 1.10.2 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.\n`Py_DECREF()` also frees the object when the count reaches zero.\nFor flexibility, it doesn't call `free()` directly -- rather, it\nmakes a call through a function pointer in the object's type\nobject. For this purpose (and others), every object also contains a\npointer to its type object.\nThe big question now remains: when to use `Py_INCREF(x)` and\n`Py_DECREF(x)`? Let's first introduce some terms. Nobody\n``owns'' an object; however, you can own a reference to an\nobject. An object's reference count is now defined as the number of\nowned references to it. The owner of a reference is responsible for\ncalling `Py_DECREF()` when the reference is no longer 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\n`Py_DECREF()`. Forgetting to dispose of an owned reference creates\na memory leak.\nIt is also possible to borrowfootnode.html#372 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#537\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\n`Py_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---\nnode15.html node12.html node13.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2378, "url": "https://docs.python.org/{python_version}/ext/node14.html"} {"title": "1.10.3 Ownership Rules", "text": "node16.html node12.html node14.html node1.html node38.html\n---\n## 1.10.3 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\n`Py_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,\n`PyInt_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\n`PyObject_GetAttrString()`. The picture is less clear, here,\nhowever, since a few common routines are exceptions:\n`PyTuple_GetItem()`, `PyList_GetItem()` and\n`PyDict_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\n`sys.modules`.\nWhen you pass an object reference into another function, in general,\nthe function borrows the reference from you -- if it needs to store\nit, it will use `Py_INCREF()` to become an independent owner.\nThere are exactly two important exceptions to this rule:\n`PyTuple_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\n`Py_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---\nnode16.html node12.html node14.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2443, "url": "https://docs.python.org/{python_version}/ext/node15.html"} {"title": "1.10.4 Thin Ice", "text": "node17.html node12.html node15.html node1.html node38.html\n---\n## 1.10.4 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\n`Py_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\n`del list[0]`, and assuming this was the last reference to that\nobject, it would free the memory associated with it, thereby\ninvalidating `item`.\nThe solution, once you know the source of the problem, is easy:\ntemporarily increment the reference count. The correct version of the\nfunction reads:\n```text\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\n`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using\n`Py_END_ALLOW_THREADS`. This is common around blocking I/O\ncalls, to let other threads use the CPU while waiting for the I/O to\ncomplete. Obviously, the following function has the same problem as\nthe previous one:\n```text\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---\nnode17.html node12.html node15.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3086, "url": "https://docs.python.org/{python_version}/ext/node16.html"} {"title": "1.10.5 NULL Pointers", "text": "node18.html node12.html node16.html node1.html node38.html\n---\n## 1.10.5 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\n`malloc()` 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\n`Py_XINCREF()` and `Py_XDECREF()` do.\nThe macros for checking for a particular object type\n(`Py type _Check()`) don't check for `NULL` pointers --\nagain, there is much code that calls several of these in a row to test\nan object against various different expected types, and this would\ngenerate redundant tests. There are no variants with `NULL`\nchecking.\nThe C function calling mechanism guarantees that the argument list\npassed to C functions (`args` in the examples) is never\n`NULL` -- in fact it guarantees that it is always a tuple.footnode.html#428\nIt is a severe error to ever let a `NULL` pointer ``escape'' to\nthe Python user.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1548, "url": "https://docs.python.org/{python_version}/ext/node17.html"} {"title": "Writing Extensions in C++", "text": "node19.html node2.html node17.html node1.html node38.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. All functions that will be called directly or\nindirectly (i.e. via function pointers) by the Python interpreter will\nhave to be declared using `extern \"C\"`; this applies to all\n``methods'' as well as to the module's initialization function.\nIt is unnecessary to enclose the Python header files in\n`extern \"C\" {...}` -- they use this form already if the symbol\n`__cplusplus' is defined (all recent C++ compilers define this\nsymbol).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 843, "url": "https://docs.python.org/{python_version}/ext/node18.html"} {"title": "2 Embedding Python in another application", "text": "node20.html ext.html node18.html node1.html node38.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++ (node20.html#SECTION00310000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1387, "url": "https://docs.python.org/{python_version}/ext/node19.html"} {"title": "Extending Python with C or C++ code", "text": "node3.html ext.html node1.html node1.html node38.html\n---\n# Extending Python with C or C++ code\n---\n- 1.1 Introduction (node3.html#SECTION00210000000000000000)\n1.2 A Simple Example (node4.html#SECTION00220000000000000000)\n1.3 Intermezzo: Errors and Exceptions (node5.html#SECTION00230000000000000000)\n1.4 Back to the Example (node6.html#SECTION00240000000000000000)\n1.5 The Module's Method Table and Initialization Function (node7.html#SECTION00250000000000000000)\n1.6 Compilation and Linkage (node8.html#SECTION00260000000000000000)\n1.7 Calling Python Functions From C (node9.html#SECTION00270000000000000000)\nFormat Strings for PyArg_ParseTuple() (node10.html#SECTION00280000000000000000)\nThe Py_BuildValue() Function (node11.html#SECTION00290000000000000000)\n1.10 Reference Counts (node12.html#SECTION002100000000000000000)\n- 1.10.1 Introduction (node13.html#SECTION002101000000000000000)\n1.10.2 Reference Counting in Python (node14.html#SECTION002102000000000000000)\n1.10.3 Ownership Rules (node15.html#SECTION002103000000000000000)\n1.10.4 Thin Ice (node16.html#SECTION002104000000000000000)\n1.10.5 NULL Pointers (node17.html#SECTION002105000000000000000)\nWriting Extensions in C++ (node18.html#SECTION002110000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1256, "url": "https://docs.python.org/{python_version}/ext/node2.html"} {"title": "Embedding Python in C++", "text": "node21.html node19.html node19.html node1.html node38.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@cnri.reston.va.us", "python_version": "1.4", "length": 421, "url": "https://docs.python.org/{python_version}/ext/node20.html"} {"title": "3 Dynamic Loading", "text": "node22.html ext.html node20.html node1.html node38.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 (node22.html#SECTION00410000000000000000)\n- 3.1.1 Shared Libraries (node23.html#SECTION00411000000000000000)\n3.1.2 SGI IRIX 4 Dynamic Loading (node24.html#SECTION00412000000000000000)\n3.1.3 GNU Dynamic Loading (node25.html#SECTION00413000000000000000)\n3.2 Building a Dynamically Loadable Module (node26.html#SECTION00420000000000000000)\n- 3.2.1 Shared Libraries (node27.html#SECTION00421000000000000000)\n3.2.2 SGI IRIX 4 Dynamic Loading (node28.html#SECTION00422000000000000000)\n3.2.3 GNU Dynamic Loading (node29.html#SECTION00423000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1897, "url": "https://docs.python.org/{python_version}/ext/node21.html"} {"title": "3.1 Configuring and Building the Interpreter for Dynamic Loading", "text": "node23.html node21.html node21.html node1.html node38.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- 3.1.1 Shared Libraries (node23.html#SECTION00411000000000000000)\n3.1.2 SGI IRIX 4 Dynamic Loading (node24.html#SECTION00412000000000000000)\n3.1.3 GNU Dynamic Loading (node25.html#SECTION00413000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 515, "url": "https://docs.python.org/{python_version}/ext/node22.html"} {"title": "3.1.1 Shared Libraries", "text": "node24.html node22.html node22.html node1.html node38.html\n---\n## 3.1.1 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@cnri.reston.va.us", "python_version": "1.4", "length": 575, "url": "https://docs.python.org/{python_version}/ext/node23.html"} {"title": "3.1.2 SGI IRIX 4 Dynamic Loading", "text": "node25.html node22.html node23.html node1.html node38.html\n---\n## 3.1.2 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 host ``ftp.cwi.nl`', directory ``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@cnri.reston.va.us", "python_version": "1.4", "length": 1017, "url": "https://docs.python.org/{python_version}/ext/node24.html"} {"title": "3.1.3 GNU Dynamic Loading", "text": "node26.html node22.html node24.html node1.html node38.html\n---\n## 3.1.3 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. One is GNU DLD 3.2.3,\navailable by anonymous ftp from host ``ftp.cwi.nl`', directory\n``pub/dynload`', file ``dld-3.2.3.tar.Z`'. (As far as I know,\nno further development on GNU DLD is being done.) The other 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 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@cnri.reston.va.us", "python_version": "1.4", "length": 1354, "url": "https://docs.python.org/{python_version}/ext/node25.html"} {"title": "3.2 Building a Dynamically Loadable Module", "text": "node27.html node21.html node25.html node1.html node38.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- 3.2.1 Shared Libraries (node27.html#SECTION00421000000000000000)\n3.2.2 SGI IRIX 4 Dynamic Loading (node28.html#SECTION00422000000000000000)\n3.2.3 GNU Dynamic Loading (node29.html#SECTION00423000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1258, "url": "https://docs.python.org/{python_version}/ext/node26.html"} {"title": "3.2.1 Shared Libraries", "text": "node28.html node26.html node26.html node1.html node38.html\n---\n## 3.2.1 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 system.\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@cnri.reston.va.us", "python_version": "1.4", "length": 903, "url": "https://docs.python.org/{python_version}/ext/node27.html"} {"title": "3.2.2 SGI IRIX 4 Dynamic Loading", "text": "node29.html node26.html node27.html node1.html node38.html\n---\n## 3.2.2 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#543\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@cnri.reston.va.us", "python_version": "1.4", "length": 1292, "url": "https://docs.python.org/{python_version}/ext/node28.html"} {"title": "3.2.3 GNU Dynamic Loading", "text": "node30.html node26.html node28.html node1.html node38.html\n---\n## 3.2.3 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@cnri.reston.va.us", "python_version": "1.4", "length": 494, "url": "https://docs.python.org/{python_version}/ext/node29.html"} {"title": "1.1 Introduction", "text": "node4.html node2.html node2.html node1.html node38.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@cnri.reston.va.us", "python_version": "1.4", "length": 793, "url": "https://docs.python.org/{python_version}/ext/node3.html"} {"title": "4 Extension Reference", "text": "node31.html ext.html node29.html node1.html node38.html\n---\n# 4 Extension Reference\n---\n- 4.1 Introduction (node31.html#SECTION00510000000000000000)\n- 4.1.1 Memory Management (node32.html#SECTION00511000000000000000)\n4.2 Object Protocol (node33.html#SECTION00520000000000000000)\n4.3 Number Protocol (node34.html#SECTION00530000000000000000)\n4.4 Sequence protocol (node35.html#SECTION00540000000000000000)\n4.5 Mapping protocol (node36.html#SECTION00550000000000000000)\n4.6 Constructors (node37.html#SECTION00560000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 554, "url": "https://docs.python.org/{python_version}/ext/node30.html"} {"title": "4.1 Introduction", "text": "node32.html node30.html node30.html node1.html node38.html\n---\n# 4.1 Introduction\nFrom the viewpoint of of C access to Python services, we have:\n1. \"Very high level layer\": two or three functions that let you exec or\neval arbitrary Python code given as a string in a module whose name is\ngiven, passing C values in and getting C values out using\nmkvalue/getargs style format strings. This does not require the user\nto declare any variables of type \"PyObject *\". This should be enough\nto write a simple application that gets Python code from the user,\nexecs it, and returns the output or errors.\"Abstract objects layer\": which is the subject of this chapter.\nIt has many functions operating on objects, and lest you do many\nthings from C that you can also write in Python, without going\nthrough the Python parser.\"Concrete objects layer\": This is the public type-dependent\ninterface provided by the standard built-in types, such as floats,\nstrings, and lists. This interface exists and is currently\ndocumented by the collection of include files provides with the\nPython distributions.\nFrom the point of view of Python accessing services provided by C\nmodules:\"Python module interface\": this interface consist of the basic\nroutines used to define modules and their members. Most of the\ncurrent extensions-writing guide deals with this interface.\"Built-in object interface\": this is the interface that a new\nbuilt-in type must provide and the mechanisms and rules that a\ndeveloper of a new built-in type must use and follow.\nThe Python C object interface provides four protocols: object,\nnumeric, sequence, and mapping. Each protocol consists of a\ncollection of related operations. If an operation that is not\nprovided by a particular type is invoked, then a standard exception,\nNotImplementedError is raised with a operation name as an argument.\nIn addition, for convenience this interface defines a set of\nconstructors for building objects of built-in types. This is needed\nso new objects can be returned from C functions that otherwise treat\nobjects generically.\n---\n- 4.1.1 Memory Management (node32.html#SECTION00511000000000000000)\n---\nnode32.html node30.html node30.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2221, "url": "https://docs.python.org/{python_version}/ext/node31.html"} {"title": "4.1.1 Memory Management", "text": "node33.html node31.html node31.html node1.html node38.html\n---\n## 4.1.1 Memory Management\nFor all of the functions described in this chapter, if a function\nretains a reference to a Python object passed as an argument, then the\nfunction will increase the reference count of the object. It is\nunnecessary for the caller to increase the reference count of an\nargument in anticipation of the object's retention.\nAll Python objects returned from functions should be treated as new\nobjects. Functions that return objects assume that the caller will\nretain a reference and the reference count of the object has already\nbeen incremented to account for this fact. A caller that does not\nretain a reference to an object that is returned from a function\nmust decrement the reference count of the object (using\nDECREF(object)) to prevent memory leaks.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 867, "url": "https://docs.python.org/{python_version}/ext/node32.html"} {"title": "4.2 Object Protocol", "text": "node34.html node30.html node32.html node1.html node38.html\n---\n# 4.2 Object Protocol\n---\nnode34.html node30.html node32.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 171, "url": "https://docs.python.org/{python_version}/ext/node33.html"} {"title": "4.3 Number Protocol", "text": "node35.html node30.html node33.html node1.html node38.html\n---\n# 4.3 Number Protocol\n---\nnode35.html node30.html node33.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 171, "url": "https://docs.python.org/{python_version}/ext/node34.html"} {"title": "4.4 Sequence protocol", "text": "node36.html node30.html node34.html node1.html node38.html\n---\n# 4.4 Sequence protocol\n---\nnode36.html node30.html node34.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 173, "url": "https://docs.python.org/{python_version}/ext/node35.html"} {"title": "4.5 Mapping protocol", "text": "node37.html node30.html node35.html node1.html node38.html\n---\n# 4.5 Mapping protocol\n---\nnode37.html node30.html node35.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 172, "url": "https://docs.python.org/{python_version}/ext/node36.html"} {"title": "4.6 Constructors", "text": "node38.html node30.html node36.html node1.html node38.html\n---\n# 4.6 Constructors\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 109, "url": "https://docs.python.org/{python_version}/ext/node37.html"} {"title": "Index", "text": "node39.html ext.html node37.html node1.html\n---\n## Index\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 84, "url": "https://docs.python.org/{python_version}/ext/node38.html"} {"title": "About this document ...", "text": "ext.html node38.html node1.html node38.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@cnri.reston.va.us ext.tex.\nThe translation was initiated by Fred L. Drake on Fri Dec 6 13:25:42 EST 1996\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 611, "url": "https://docs.python.org/{python_version}/ext/node39.html"} {"title": "1.2 A Simple Example", "text": "node5.html node2.html node3.html node1.html node38.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#521\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\n`realloc()` directly.\nThe next thing we add to our module file is the C function that will\nbe called when the Python expression `spam.system(string)'\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.\n`PyArg_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\n`NULL` immediately (as we saw in the example).\n---\nnode5.html node2.html node3.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3375, "url": "https://docs.python.org/{python_version}/ext/node4.html"} {"title": "1.3 Intermezzo: Errors and Exceptions", "text": "node6.html node2.html node4.html node1.html node38.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\n`sys.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\n`Py_INCREF()` the objects passed to any of these functions.\nYou can test non-destructively whether an exception has been set with\n`PyErr_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 varg 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\n`PyErr_*()` 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\n`realloc()`) 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\n`malloc()` directly this note is of importance.\nAlso note that, with the important exception of\n`PyArg_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\n`PyExc_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,\n`PyExc_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\n`spam.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 node2.html node4.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 5567, "url": "https://docs.python.org/{python_version}/ext/node5.html"} {"title": "1.4 Back to the Example", "text": "node7.html node2.html node5.html node1.html node38.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\n`command`. This is a pointer assignment and you are not supposed\nto modify the string to which it points (so in Standard C, the variable\n`command` 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 `sys`\nas a Python object. This is done using the function\n`Py_BuildValue()`, which is something like the inverse of\n`PyArg_ParseTuple()`: it takes a format string and an arbitrary\nnumber of C values, and returns a new Python object. More info on\n`Py_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\n`None`. You need this idiom to do so:\n```text\nPy_INCREF(Py_None);\nreturn Py_None;\n```\n`Py_None` is the C name for the special Python object\n`None`. It is a genuine Python object (not a `NULL`\npointer, which means ``error'' in most contexts, as we have seen).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1767, "url": "https://docs.python.org/{python_version}/ext/node6.html"} {"title": "1.5 The Module's Method Table and Initialization Function", "text": "node8.html node2.html node6.html node1.html node38.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, 1},\n...\n{NULL, NULL} /* Sentinel */\n};\n```\nNote the third entry (`1'). This is a flag telling the\ninterpreter the calling convention to be used for the C function. It\nshould normally always be `1'; a value of `0' means that an\nobsolete variant of `PyArg_ParseTuple()` is used.\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,\n`initspam()` is called. It calls `Py_InitModule()`, which\ncreates a ``module object'' (which is inserted in the dictionary\n`sys.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@cnri.reston.va.us", "python_version": "1.4", "length": 1499, "url": "https://docs.python.org/{python_version}/ext/node7.html"} {"title": "1.6 Compilation and Linkage", "text": "node9.html node2.html node7.html node1.html node38.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@cnri.reston.va.us", "python_version": "1.4", "length": 1236, "url": "https://docs.python.org/{python_version}/ext/node8.html"} {"title": "1.7 Calling Python Functions From C", "text": "node10.html node2.html node8.html node1.html node38.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\n`Py_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\n`NULL` 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\n`PyEval_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```\n`PyEval_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\n`PyErr_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 node2.html node8.html node1.html node38.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 5021, "url": "https://docs.python.org/{python_version}/ext/node9.html"} {"title": "Footnotes", "text": "guido@cnri.reston.va.us", "python_version": "1.4", "length": 23, "url": "https://docs.python.org/{python_version}/lib/footnode.html"} {"title": "Python Library Reference", "text": "node1.html node1.html node221.html\n---\n# Python Library Reference\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\nOctober 25, 1996\nRelease 1.4\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 syntactic and\nsemantic questions. Finally, the manual entitled Extending and\nEmbedding the Python Interpreter describes how to add new extensions\nto Python and how to embed it in other applications.\n---\n- Contents (node1.html#SECTION00100000000000000000)\n1 Introduction (node2.html#SECTION00200000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION00300000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION00310000000000000000)\n- 2.1.1 Truth Value Testing (node5.html#SECTION00311000000000000000)\n2.1.2 Boolean Operations (node6.html#SECTION00312000000000000000)\n2.1.3 Comparisons (node7.html#SECTION00313000000000000000)\n2.1.4 Numeric Types (node8.html#SECTION00314000000000000000)\n2.1.5 Sequence Types (node10.html#SECTION00315000000000000000)\n2.1.6 Mapping Types (node13.html#SECTION00316000000000000000)\n2.1.7 Other Built-in Types (node14.html#SECTION00317000000000000000)\n2.1.8 Special Attributes (node24.html#SECTION00318000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION00320000000000000000)\n2.3 Built-in Functions (node26.html#SECTION00330000000000000000)\n3 Python Services (node27.html#SECTION00400000000000000000)\n- 3.1 Built-in Module `sys` (node28.html#SECTION00410000000000000000)\n3.2 Standard Module `types` (node29.html#SECTION00420000000000000000)\n3.3 Standard Module `traceback` (node30.html#SECTION00430000000000000000)\n3.4 Standard Module `pickle` (node31.html#SECTION00440000000000000000)\n3.5 Standard Module `shelve` (node32.html#SECTION00450000000000000000)\n3.6 Standard Module `copy` (node33.html#SECTION00460000000000000000)\n3.7 Built-in Module `marshal` (node34.html#SECTION00470000000000000000)\n3.8 Built-in Module `imp` (node35.html#SECTION00480000000000000000)\n- 3.8.1 Examples (node36.html#SECTION00481000000000000000)\n3.9 Built-in Module `parser` (node37.html#SECTION00490000000000000000)\n- 3.9.1 Creating AST Objects (node38.html#SECTION00491000000000000000)\n3.9.2 Converting AST Objects (node39.html#SECTION00492000000000000000)\n3.9.3 Queries on AST Objects (node40.html#SECTION00493000000000000000)\n3.9.4 Exceptions and Error Handling (node41.html#SECTION00494000000000000000)\n3.9.5 AST Objects (node42.html#SECTION00495000000000000000)\n3.9.6 Examples (node43.html#SECTION00496000000000000000)\n3.10 Built-in Module `__builtin__` (node46.html#SECTION004100000000000000000)\n3.11 Built-in Module `__main__` (node47.html#SECTION004110000000000000000)\n4 String Services (node48.html#SECTION00500000000000000000)\n- 4.1 Standard Module `string` (node49.html#SECTION00510000000000000000)\n4.2 Built-in Module `regex` (node50.html#SECTION00520000000000000000)\n- 4.2.1 Regular Expressions (node51.html#SECTION00521000000000000000)\n4.2.2 Module Contents (node52.html#SECTION00522000000000000000)\n4.3 Standard Module `regsub` (node53.html#SECTION00530000000000000000)\n4.4 Built-in Module `struct` (node54.html#SECTION00540000000000000000)\n5 Miscellaneous Services (node55.html#SECTION00600000000000000000)\n- 5.1 Built-in Module `math` (node56.html#SECTION00610000000000000000)\n5.2 Standard Module `rand` (node57.html#SECTION00620000000000000000)\n5.3 Standard Module `whrandom` (node58.html#SECTION00630000000000000000)\n5.4 Built-in Module `array` (node59.html#SECTION00640000000000000000)\n6 Generic Operating System Services (node60.html#SECTION00700000000000000000)\n- 6.1 Standard Module `os` (node61.html#SECTION00710000000000000000)\n6.2 Built-in Module `time` (node62.html#SECTION00720000000000000000)\n6.3 Standard Module `getopt` (node63.html#SECTION00730000000000000000)\n6.4 Standard Module `tempfile` (node64.html#SECTION00740000000000000000)\n6.5 Standard Module `errno` (node65.html#SECTION00750000000000000000)\n7 Optional Operating System Services (node66.html#SECTION00800000000000000000)\n- 7.1 Built-in Module `signal` (node67.html#SECTION00810000000000000000)\n7.2 Built-in Module `socket` (node68.html#SECTION00820000000000000000)\n- 7.2.1 Socket Objects (node69.html#SECTION00821000000000000000)\n7.2.2 Example (node70.html#SECTION00822000000000000000)\n7.3 Built-in Module `select` (node71.html#SECTION00830000000000000000)\n7.4 Built-in Module `thread` (node72.html#SECTION00840000000000000000)\n8 UNIX Specific Services (node73.html#SECTION00900000000000000000)\n- 8.1 Built-in Module `posix` (node74.html#SECTION00910000000000000000)\n8.2 Standard Module `posixpath` (node75.html#SECTION00920000000000000000)\n8.3 Built-in Module `pwd` (node76.html#SECTION00930000000000000000)\n8.4 Built-in Module `grp` (node77.html#SECTION00940000000000000000)\n8.5 Built-in module crypt (node78.html#SECTION00950000000000000000)\n8.6 Built-in Module `dbm` (node79.html#SECTION00960000000000000000)\n8.7 Built-in Module `gdbm` (node80.html#SECTION00970000000000000000)\n8.8 Built-in Module `termios` (node81.html#SECTION00980000000000000000)\n- 8.8.1 Example (node82.html#SECTION00981000000000000000)\n8.9 Standard Module `TERMIOS` (node83.html#SECTION00990000000000000000)\n8.10 Built-in Module `fcntl` (node84.html#SECTION009100000000000000000)\n8.11 Standard Module `posixfile` (node85.html#SECTION009110000000000000000)\n8.12 Built-in Module `syslog` (node86.html#SECTION009120000000000000000)\n9 The Python Debugger (node87.html#SECTION001000000000000000000)\n- 9.1 Debugger Commands (node88.html#SECTION001010000000000000000)\n9.2 How It Works (node89.html#SECTION001020000000000000000)\n10 The Python Profiler (node90.html#SECTION001100000000000000000)\n- 10.1 Introduction to the profiler (node91.html#SECTION001110000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node92.html#SECTION001120000000000000000)\n10.3 Instant Users Manual (node93.html#SECTION001130000000000000000)\n10.4 What Is Deterministic Profiling? (node94.html#SECTION001140000000000000000)\n10.5 Reference Manual (node95.html#SECTION001150000000000000000)\n- 10.5.1 The `Stats` Class (node96.html#SECTION001151000000000000000)\n10.6 Limitations (node97.html#SECTION001160000000000000000)\n10.7 Calibration (node98.html#SECTION001170000000000000000)\n10.8 Extensions - Deriving Better Profilers (node99.html#SECTION001180000000000000000)\n- 10.8.1 OldProfile Class (node100.html#SECTION001181000000000000000)\n10.8.2 HotProfile Class (node101.html#SECTION001182000000000000000)\n11 Internet and WWW Services (node102.html#SECTION001200000000000000000)\n- 11.1 Standard Module `cgi` (node103.html#SECTION001210000000000000000)\n- 11.1.1 Introduction (node104.html#SECTION001211000000000000000)\n11.1.2 Using the cgi module (node105.html#SECTION001212000000000000000)\n11.1.3 Old classes (node106.html#SECTION001213000000000000000)\n11.1.4 Functions (node107.html#SECTION001214000000000000000)\n11.1.5 Caring about security (node108.html#SECTION001215000000000000000)\n11.1.6 Installing your CGI script on a Unix system (node109.html#SECTION001216000000000000000)\n11.1.7 Testing your CGI script (node110.html#SECTION001217000000000000000)\n11.1.8 Debugging CGI scripts (node111.html#SECTION001218000000000000000)\n11.1.9 Common problems and solutions (node112.html#SECTION001219000000000000000)\n11.2 Standard Module `urllib` (node113.html#SECTION001220000000000000000)\n11.3 Standard Module `httplib` (node114.html#SECTION001230000000000000000)\n- 11.3.1 HTTP Objects (node115.html#SECTION001231000000000000000)\n11.3.2 Example (node116.html#SECTION001232000000000000000)\n11.4 Standard Module `ftplib` (node117.html#SECTION001240000000000000000)\n- 11.4.1 FTP Objects (node118.html#SECTION001241000000000000000)\n11.5 Standard Module `gopherlib` (node119.html#SECTION001250000000000000000)\n11.6 Standard Module `nntplib` (node120.html#SECTION001260000000000000000)\n- 11.6.1 NNTP Objects (node121.html#SECTION001261000000000000000)\n11.7 Standard Module `urlparse` (node122.html#SECTION001270000000000000000)\n11.8 Standard Module `sgmllib` (node123.html#SECTION001280000000000000000)\n11.9 Standard Module `htmllib` (node124.html#SECTION001290000000000000000)\n11.10 Standard Module `formatter` (node125.html#SECTION0012100000000000000000)\n- 11.10.1 The Formatter Interface (node126.html#SECTION0012101000000000000000)\n11.10.2 Formatter Implementations (node127.html#SECTION0012102000000000000000)\n11.10.3 The Writer Interface (node128.html#SECTION0012103000000000000000)\n11.10.4 Writer Implementations (node129.html#SECTION0012104000000000000000)\n11.11 Standard Module `rfc822` (node130.html#SECTION0012110000000000000000)\n- 11.11.1 Message Objects (node131.html#SECTION0012111000000000000000)\n11.12 Standard Module `mimetools` (node132.html#SECTION0012120000000000000000)\n- 11.12.1 Additional Methods of Message objects (node133.html#SECTION0012121000000000000000)\n11.13 Standard module `binhex` (node134.html#SECTION0012130000000000000000)\n- 11.13.1 notes (node135.html#SECTION0012131000000000000000)\n11.14 Standard module `uu` (node136.html#SECTION0012140000000000000000)\n11.15 Built-in Module `binascii` (node137.html#SECTION0012150000000000000000)\n11.16 Standard module `xdrlib` (node138.html#SECTION0012160000000000000000)\n- 11.16.1 Packer Objects (node139.html#SECTION0012161000000000000000)\n11.16.2 Unpacker Objects (node140.html#SECTION0012162000000000000000)\n11.16.3 Exceptions (node141.html#SECTION0012163000000000000000)\n11.16.4 Supporting Floating Point Data (node142.html#SECTION0012164000000000000000)\n12 Restricted Execution (node143.html#SECTION001300000000000000000)\n- 12.1 Standard Module `rexec` (node144.html#SECTION001310000000000000000)\n- 12.1.1 An example (node145.html#SECTION001311000000000000000)\n12.2 Standard Module `Bastion` (node146.html#SECTION001320000000000000000)\n13 Multimedia Services (node147.html#SECTION001400000000000000000)\n- 13.1 Built-in Module `audioop` (node148.html#SECTION001410000000000000000)\n13.2 Built-in Module `imageop` (node149.html#SECTION001420000000000000000)\n13.3 Standard Module `aifc` (node150.html#SECTION001430000000000000000)\n13.4 Built-in Module `jpeg` (node151.html#SECTION001440000000000000000)\n13.5 Built-in Module `rgbimg` (node152.html#SECTION001450000000000000000)\n13.6 Standard module `imghdr` (node153.html#SECTION001460000000000000000)\n14 Cryptographic Services (node154.html#SECTION001500000000000000000)\n- 14.1 Built-in Module `md5` (node155.html#SECTION001510000000000000000)\n14.2 Built-in Module `mpz` (node156.html#SECTION001520000000000000000)\n14.3 Built-in Module `rotor` (node157.html#SECTION001530000000000000000)\n15 Macintosh Specific Services (node158.html#SECTION001600000000000000000)\n- 15.1 Built-in Module `mac` (node159.html#SECTION001610000000000000000)\n15.2 Standard Module `macpath` (node160.html#SECTION001620000000000000000)\n15.3 Built-in Module `ctb` (node161.html#SECTION001630000000000000000)\n- 15.3.1 connection object (node162.html#SECTION001631000000000000000)\n15.4 Built-in Module `macconsole` (node163.html#SECTION001640000000000000000)\n- 15.4.1 macconsole options object (node164.html#SECTION001641000000000000000)\n15.4.2 console window object (node165.html#SECTION001642000000000000000)\n15.5 Built-in Module `macdnr` (node166.html#SECTION001650000000000000000)\n- 15.5.1 dnr result object (node167.html#SECTION001651000000000000000)\n15.6 Built-in Module `macfs` (node168.html#SECTION001660000000000000000)\n- 15.6.1 FSSpec objects (node169.html#SECTION001661000000000000000)\n15.6.2 alias objects (node170.html#SECTION001662000000000000000)\n15.6.3 FInfo objects (node171.html#SECTION001663000000000000000)\n15.7 Built-in Module `MacOS` (node172.html#SECTION001670000000000000000)\n15.8 Standard module `macostools` (node173.html#SECTION001680000000000000000)\n15.9 Standard module `findertools` (node174.html#SECTION001690000000000000000)\n15.10 Built-in Module `mactcp` (node175.html#SECTION0016100000000000000000)\n- 15.10.1 TCP Stream Objects (node176.html#SECTION0016101000000000000000)\n15.10.2 TCP Status Objects (node177.html#SECTION0016102000000000000000)\n15.10.3 UDP Stream Objects (node178.html#SECTION0016103000000000000000)\n15.11 Built-in Module `macspeech` (node179.html#SECTION0016110000000000000000)\n- 15.11.1 voice objects (node180.html#SECTION0016111000000000000000)\n15.11.2 speech channel objects (node181.html#SECTION0016112000000000000000)\n15.12 Standard module `EasyDialogs` (node182.html#SECTION0016120000000000000000)\n15.13 Standard module `FrameWork` (node183.html#SECTION0016130000000000000000)\n- 15.13.1 Application objects (node184.html#SECTION0016131000000000000000)\n15.13.2 Window Objects (node185.html#SECTION0016132000000000000000)\n15.13.3 ControlsWindow Object (node186.html#SECTION0016133000000000000000)\n15.13.4 ScrolledWindow Object (node187.html#SECTION0016134000000000000000)\n15.13.5 DialogWindow Objects (node188.html#SECTION0016135000000000000000)\n15.14 Standard module `MiniAEFrame` (node189.html#SECTION0016140000000000000000)\n- 15.14.1 AEServer Objects (node190.html#SECTION0016141000000000000000)\n16 Standard Windowing Interface (node191.html#SECTION001700000000000000000)\n- 16.1 Built-in Module `stdwin` (node192.html#SECTION001710000000000000000)\n- 16.1.1 Functions Defined in Module `stdwin` (node193.html#SECTION001711000000000000000)\n16.1.2 Window Objects (node194.html#SECTION001712000000000000000)\n16.1.3 Drawing Objects (node195.html#SECTION001713000000000000000)\n16.1.4 Menu Objects (node196.html#SECTION001714000000000000000)\n16.1.5 Bitmap Objects (node197.html#SECTION001715000000000000000)\n16.1.6 Text-edit Objects (node198.html#SECTION001716000000000000000)\n16.1.7 Example (node199.html#SECTION001717000000000000000)\n16.2 Standard Module `stdwinevents` (node200.html#SECTION001720000000000000000)\n16.3 Standard Module `rect` (node201.html#SECTION001730000000000000000)\n17 SGI IRIX Specific Services (node202.html#SECTION001800000000000000000)\n- 17.1 Built-in Module `al` (node203.html#SECTION001810000000000000000)\n- 17.1.1 Configuration Objects (node204.html#SECTION001811000000000000000)\n17.1.2 Port Objects (node205.html#SECTION001812000000000000000)\n17.2 Standard Module `AL` (node206.html#SECTION001820000000000000000)\n17.3 Built-in Module `cd` (node207.html#SECTION001830000000000000000)\n17.4 Built-in Module `fl` (node208.html#SECTION001840000000000000000)\n- 17.4.1 Functions Defined in Module `fl` (node209.html#SECTION001841000000000000000)\n17.4.2 Form Objects (node210.html#SECTION001842000000000000000)\n17.4.3 FORMS Objects (node211.html#SECTION001843000000000000000)\n17.5 Standard Module `FL` (node212.html#SECTION001850000000000000000)\n17.6 Standard Module `flp` (node213.html#SECTION001860000000000000000)\n17.7 Built-in Module `fm` (node214.html#SECTION001870000000000000000)\n17.8 Built-in Module `gl` (node215.html#SECTION001880000000000000000)\n17.9 Standard Modules `GL` and `DEVICE` (node216.html#SECTION001890000000000000000)\n17.10 Built-in Module `imgfile` (node217.html#SECTION0018100000000000000000)\n18 SunOS Specific Services (node218.html#SECTION001900000000000000000)\n- 18.1 Built-in Module `sunaudiodev` (node219.html#SECTION001910000000000000000)\n- 18.1.1 Audio Device Objects (node220.html#SECTION001911000000000000000)\nIndex (node221.html#SECTION002000000000000000000)\nAbout this document ... (node222.html#SECTION002100000000000000000)\n---\nnode1.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 18142, "url": "https://docs.python.org/{python_version}/lib/index.html"} {"title": "Python Library Reference", "text": "node1.html node1.html node221.html\n---\n# Python Library Reference\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\nOctober 25, 1996\nRelease 1.4\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 syntactic and\nsemantic questions. Finally, the manual entitled Extending and\nEmbedding the Python Interpreter describes how to add new extensions\nto Python and how to embed it in other applications.\n---\n- Contents (node1.html#SECTION00100000000000000000)\n1 Introduction (node2.html#SECTION00200000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION00300000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION00310000000000000000)\n- 2.1.1 Truth Value Testing (node5.html#SECTION00311000000000000000)\n2.1.2 Boolean Operations (node6.html#SECTION00312000000000000000)\n2.1.3 Comparisons (node7.html#SECTION00313000000000000000)\n2.1.4 Numeric Types (node8.html#SECTION00314000000000000000)\n2.1.5 Sequence Types (node10.html#SECTION00315000000000000000)\n2.1.6 Mapping Types (node13.html#SECTION00316000000000000000)\n2.1.7 Other Built-in Types (node14.html#SECTION00317000000000000000)\n2.1.8 Special Attributes (node24.html#SECTION00318000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION00320000000000000000)\n2.3 Built-in Functions (node26.html#SECTION00330000000000000000)\n3 Python Services (node27.html#SECTION00400000000000000000)\n- 3.1 Built-in Module `sys` (node28.html#SECTION00410000000000000000)\n3.2 Standard Module `types` (node29.html#SECTION00420000000000000000)\n3.3 Standard Module `traceback` (node30.html#SECTION00430000000000000000)\n3.4 Standard Module `pickle` (node31.html#SECTION00440000000000000000)\n3.5 Standard Module `shelve` (node32.html#SECTION00450000000000000000)\n3.6 Standard Module `copy` (node33.html#SECTION00460000000000000000)\n3.7 Built-in Module `marshal` (node34.html#SECTION00470000000000000000)\n3.8 Built-in Module `imp` (node35.html#SECTION00480000000000000000)\n- 3.8.1 Examples (node36.html#SECTION00481000000000000000)\n3.9 Built-in Module `parser` (node37.html#SECTION00490000000000000000)\n- 3.9.1 Creating AST Objects (node38.html#SECTION00491000000000000000)\n3.9.2 Converting AST Objects (node39.html#SECTION00492000000000000000)\n3.9.3 Queries on AST Objects (node40.html#SECTION00493000000000000000)\n3.9.4 Exceptions and Error Handling (node41.html#SECTION00494000000000000000)\n3.9.5 AST Objects (node42.html#SECTION00495000000000000000)\n3.9.6 Examples (node43.html#SECTION00496000000000000000)\n3.10 Built-in Module `__builtin__` (node46.html#SECTION004100000000000000000)\n3.11 Built-in Module `__main__` (node47.html#SECTION004110000000000000000)\n4 String Services (node48.html#SECTION00500000000000000000)\n- 4.1 Standard Module `string` (node49.html#SECTION00510000000000000000)\n4.2 Built-in Module `regex` (node50.html#SECTION00520000000000000000)\n- 4.2.1 Regular Expressions (node51.html#SECTION00521000000000000000)\n4.2.2 Module Contents (node52.html#SECTION00522000000000000000)\n4.3 Standard Module `regsub` (node53.html#SECTION00530000000000000000)\n4.4 Built-in Module `struct` (node54.html#SECTION00540000000000000000)\n5 Miscellaneous Services (node55.html#SECTION00600000000000000000)\n- 5.1 Built-in Module `math` (node56.html#SECTION00610000000000000000)\n5.2 Standard Module `rand` (node57.html#SECTION00620000000000000000)\n5.3 Standard Module `whrandom` (node58.html#SECTION00630000000000000000)\n5.4 Built-in Module `array` (node59.html#SECTION00640000000000000000)\n6 Generic Operating System Services (node60.html#SECTION00700000000000000000)\n- 6.1 Standard Module `os` (node61.html#SECTION00710000000000000000)\n6.2 Built-in Module `time` (node62.html#SECTION00720000000000000000)\n6.3 Standard Module `getopt` (node63.html#SECTION00730000000000000000)\n6.4 Standard Module `tempfile` (node64.html#SECTION00740000000000000000)\n6.5 Standard Module `errno` (node65.html#SECTION00750000000000000000)\n7 Optional Operating System Services (node66.html#SECTION00800000000000000000)\n- 7.1 Built-in Module `signal` (node67.html#SECTION00810000000000000000)\n7.2 Built-in Module `socket` (node68.html#SECTION00820000000000000000)\n- 7.2.1 Socket Objects (node69.html#SECTION00821000000000000000)\n7.2.2 Example (node70.html#SECTION00822000000000000000)\n7.3 Built-in Module `select` (node71.html#SECTION00830000000000000000)\n7.4 Built-in Module `thread` (node72.html#SECTION00840000000000000000)\n8 UNIX Specific Services (node73.html#SECTION00900000000000000000)\n- 8.1 Built-in Module `posix` (node74.html#SECTION00910000000000000000)\n8.2 Standard Module `posixpath` (node75.html#SECTION00920000000000000000)\n8.3 Built-in Module `pwd` (node76.html#SECTION00930000000000000000)\n8.4 Built-in Module `grp` (node77.html#SECTION00940000000000000000)\n8.5 Built-in module crypt (node78.html#SECTION00950000000000000000)\n8.6 Built-in Module `dbm` (node79.html#SECTION00960000000000000000)\n8.7 Built-in Module `gdbm` (node80.html#SECTION00970000000000000000)\n8.8 Built-in Module `termios` (node81.html#SECTION00980000000000000000)\n- 8.8.1 Example (node82.html#SECTION00981000000000000000)\n8.9 Standard Module `TERMIOS` (node83.html#SECTION00990000000000000000)\n8.10 Built-in Module `fcntl` (node84.html#SECTION009100000000000000000)\n8.11 Standard Module `posixfile` (node85.html#SECTION009110000000000000000)\n8.12 Built-in Module `syslog` (node86.html#SECTION009120000000000000000)\n9 The Python Debugger (node87.html#SECTION001000000000000000000)\n- 9.1 Debugger Commands (node88.html#SECTION001010000000000000000)\n9.2 How It Works (node89.html#SECTION001020000000000000000)\n10 The Python Profiler (node90.html#SECTION001100000000000000000)\n- 10.1 Introduction to the profiler (node91.html#SECTION001110000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node92.html#SECTION001120000000000000000)\n10.3 Instant Users Manual (node93.html#SECTION001130000000000000000)\n10.4 What Is Deterministic Profiling? (node94.html#SECTION001140000000000000000)\n10.5 Reference Manual (node95.html#SECTION001150000000000000000)\n- 10.5.1 The `Stats` Class (node96.html#SECTION001151000000000000000)\n10.6 Limitations (node97.html#SECTION001160000000000000000)\n10.7 Calibration (node98.html#SECTION001170000000000000000)\n10.8 Extensions - Deriving Better Profilers (node99.html#SECTION001180000000000000000)\n- 10.8.1 OldProfile Class (node100.html#SECTION001181000000000000000)\n10.8.2 HotProfile Class (node101.html#SECTION001182000000000000000)\n11 Internet and WWW Services (node102.html#SECTION001200000000000000000)\n- 11.1 Standard Module `cgi` (node103.html#SECTION001210000000000000000)\n- 11.1.1 Introduction (node104.html#SECTION001211000000000000000)\n11.1.2 Using the cgi module (node105.html#SECTION001212000000000000000)\n11.1.3 Old classes (node106.html#SECTION001213000000000000000)\n11.1.4 Functions (node107.html#SECTION001214000000000000000)\n11.1.5 Caring about security (node108.html#SECTION001215000000000000000)\n11.1.6 Installing your CGI script on a Unix system (node109.html#SECTION001216000000000000000)\n11.1.7 Testing your CGI script (node110.html#SECTION001217000000000000000)\n11.1.8 Debugging CGI scripts (node111.html#SECTION001218000000000000000)\n11.1.9 Common problems and solutions (node112.html#SECTION001219000000000000000)\n11.2 Standard Module `urllib` (node113.html#SECTION001220000000000000000)\n11.3 Standard Module `httplib` (node114.html#SECTION001230000000000000000)\n- 11.3.1 HTTP Objects (node115.html#SECTION001231000000000000000)\n11.3.2 Example (node116.html#SECTION001232000000000000000)\n11.4 Standard Module `ftplib` (node117.html#SECTION001240000000000000000)\n- 11.4.1 FTP Objects (node118.html#SECTION001241000000000000000)\n11.5 Standard Module `gopherlib` (node119.html#SECTION001250000000000000000)\n11.6 Standard Module `nntplib` (node120.html#SECTION001260000000000000000)\n- 11.6.1 NNTP Objects (node121.html#SECTION001261000000000000000)\n11.7 Standard Module `urlparse` (node122.html#SECTION001270000000000000000)\n11.8 Standard Module `sgmllib` (node123.html#SECTION001280000000000000000)\n11.9 Standard Module `htmllib` (node124.html#SECTION001290000000000000000)\n11.10 Standard Module `formatter` (node125.html#SECTION0012100000000000000000)\n- 11.10.1 The Formatter Interface (node126.html#SECTION0012101000000000000000)\n11.10.2 Formatter Implementations (node127.html#SECTION0012102000000000000000)\n11.10.3 The Writer Interface (node128.html#SECTION0012103000000000000000)\n11.10.4 Writer Implementations (node129.html#SECTION0012104000000000000000)\n11.11 Standard Module `rfc822` (node130.html#SECTION0012110000000000000000)\n- 11.11.1 Message Objects (node131.html#SECTION0012111000000000000000)\n11.12 Standard Module `mimetools` (node132.html#SECTION0012120000000000000000)\n- 11.12.1 Additional Methods of Message objects (node133.html#SECTION0012121000000000000000)\n11.13 Standard module `binhex` (node134.html#SECTION0012130000000000000000)\n- 11.13.1 notes (node135.html#SECTION0012131000000000000000)\n11.14 Standard module `uu` (node136.html#SECTION0012140000000000000000)\n11.15 Built-in Module `binascii` (node137.html#SECTION0012150000000000000000)\n11.16 Standard module `xdrlib` (node138.html#SECTION0012160000000000000000)\n- 11.16.1 Packer Objects (node139.html#SECTION0012161000000000000000)\n11.16.2 Unpacker Objects (node140.html#SECTION0012162000000000000000)\n11.16.3 Exceptions (node141.html#SECTION0012163000000000000000)\n11.16.4 Supporting Floating Point Data (node142.html#SECTION0012164000000000000000)\n12 Restricted Execution (node143.html#SECTION001300000000000000000)\n- 12.1 Standard Module `rexec` (node144.html#SECTION001310000000000000000)\n- 12.1.1 An example (node145.html#SECTION001311000000000000000)\n12.2 Standard Module `Bastion` (node146.html#SECTION001320000000000000000)\n13 Multimedia Services (node147.html#SECTION001400000000000000000)\n- 13.1 Built-in Module `audioop` (node148.html#SECTION001410000000000000000)\n13.2 Built-in Module `imageop` (node149.html#SECTION001420000000000000000)\n13.3 Standard Module `aifc` (node150.html#SECTION001430000000000000000)\n13.4 Built-in Module `jpeg` (node151.html#SECTION001440000000000000000)\n13.5 Built-in Module `rgbimg` (node152.html#SECTION001450000000000000000)\n13.6 Standard module `imghdr` (node153.html#SECTION001460000000000000000)\n14 Cryptographic Services (node154.html#SECTION001500000000000000000)\n- 14.1 Built-in Module `md5` (node155.html#SECTION001510000000000000000)\n14.2 Built-in Module `mpz` (node156.html#SECTION001520000000000000000)\n14.3 Built-in Module `rotor` (node157.html#SECTION001530000000000000000)\n15 Macintosh Specific Services (node158.html#SECTION001600000000000000000)\n- 15.1 Built-in Module `mac` (node159.html#SECTION001610000000000000000)\n15.2 Standard Module `macpath` (node160.html#SECTION001620000000000000000)\n15.3 Built-in Module `ctb` (node161.html#SECTION001630000000000000000)\n- 15.3.1 connection object (node162.html#SECTION001631000000000000000)\n15.4 Built-in Module `macconsole` (node163.html#SECTION001640000000000000000)\n- 15.4.1 macconsole options object (node164.html#SECTION001641000000000000000)\n15.4.2 console window object (node165.html#SECTION001642000000000000000)\n15.5 Built-in Module `macdnr` (node166.html#SECTION001650000000000000000)\n- 15.5.1 dnr result object (node167.html#SECTION001651000000000000000)\n15.6 Built-in Module `macfs` (node168.html#SECTION001660000000000000000)\n- 15.6.1 FSSpec objects (node169.html#SECTION001661000000000000000)\n15.6.2 alias objects (node170.html#SECTION001662000000000000000)\n15.6.3 FInfo objects (node171.html#SECTION001663000000000000000)\n15.7 Built-in Module `MacOS` (node172.html#SECTION001670000000000000000)\n15.8 Standard module `macostools` (node173.html#SECTION001680000000000000000)\n15.9 Standard module `findertools` (node174.html#SECTION001690000000000000000)\n15.10 Built-in Module `mactcp` (node175.html#SECTION0016100000000000000000)\n- 15.10.1 TCP Stream Objects (node176.html#SECTION0016101000000000000000)\n15.10.2 TCP Status Objects (node177.html#SECTION0016102000000000000000)\n15.10.3 UDP Stream Objects (node178.html#SECTION0016103000000000000000)\n15.11 Built-in Module `macspeech` (node179.html#SECTION0016110000000000000000)\n- 15.11.1 voice objects (node180.html#SECTION0016111000000000000000)\n15.11.2 speech channel objects (node181.html#SECTION0016112000000000000000)\n15.12 Standard module `EasyDialogs` (node182.html#SECTION0016120000000000000000)\n15.13 Standard module `FrameWork` (node183.html#SECTION0016130000000000000000)\n- 15.13.1 Application objects (node184.html#SECTION0016131000000000000000)\n15.13.2 Window Objects (node185.html#SECTION0016132000000000000000)\n15.13.3 ControlsWindow Object (node186.html#SECTION0016133000000000000000)\n15.13.4 ScrolledWindow Object (node187.html#SECTION0016134000000000000000)\n15.13.5 DialogWindow Objects (node188.html#SECTION0016135000000000000000)\n15.14 Standard module `MiniAEFrame` (node189.html#SECTION0016140000000000000000)\n- 15.14.1 AEServer Objects (node190.html#SECTION0016141000000000000000)\n16 Standard Windowing Interface (node191.html#SECTION001700000000000000000)\n- 16.1 Built-in Module `stdwin` (node192.html#SECTION001710000000000000000)\n- 16.1.1 Functions Defined in Module `stdwin` (node193.html#SECTION001711000000000000000)\n16.1.2 Window Objects (node194.html#SECTION001712000000000000000)\n16.1.3 Drawing Objects (node195.html#SECTION001713000000000000000)\n16.1.4 Menu Objects (node196.html#SECTION001714000000000000000)\n16.1.5 Bitmap Objects (node197.html#SECTION001715000000000000000)\n16.1.6 Text-edit Objects (node198.html#SECTION001716000000000000000)\n16.1.7 Example (node199.html#SECTION001717000000000000000)\n16.2 Standard Module `stdwinevents` (node200.html#SECTION001720000000000000000)\n16.3 Standard Module `rect` (node201.html#SECTION001730000000000000000)\n17 SGI IRIX Specific Services (node202.html#SECTION001800000000000000000)\n- 17.1 Built-in Module `al` (node203.html#SECTION001810000000000000000)\n- 17.1.1 Configuration Objects (node204.html#SECTION001811000000000000000)\n17.1.2 Port Objects (node205.html#SECTION001812000000000000000)\n17.2 Standard Module `AL` (node206.html#SECTION001820000000000000000)\n17.3 Built-in Module `cd` (node207.html#SECTION001830000000000000000)\n17.4 Built-in Module `fl` (node208.html#SECTION001840000000000000000)\n- 17.4.1 Functions Defined in Module `fl` (node209.html#SECTION001841000000000000000)\n17.4.2 Form Objects (node210.html#SECTION001842000000000000000)\n17.4.3 FORMS Objects (node211.html#SECTION001843000000000000000)\n17.5 Standard Module `FL` (node212.html#SECTION001850000000000000000)\n17.6 Standard Module `flp` (node213.html#SECTION001860000000000000000)\n17.7 Built-in Module `fm` (node214.html#SECTION001870000000000000000)\n17.8 Built-in Module `gl` (node215.html#SECTION001880000000000000000)\n17.9 Standard Modules `GL` and `DEVICE` (node216.html#SECTION001890000000000000000)\n17.10 Built-in Module `imgfile` (node217.html#SECTION0018100000000000000000)\n18 SunOS Specific Services (node218.html#SECTION001900000000000000000)\n- 18.1 Built-in Module `sunaudiodev` (node219.html#SECTION001910000000000000000)\n- 18.1.1 Audio Device Objects (node220.html#SECTION001911000000000000000)\nIndex (node221.html#SECTION002000000000000000000)\nAbout this document ... (node222.html#SECTION002100000000000000000)\n---\nnode1.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 18142, "url": "https://docs.python.org/{python_version}/lib/lib.html"} {"title": "Contents", "text": "node2.html lib.html lib.html node221.html\n---\n## Contents\n- 1 Introduction (node2.html#SECTION00200000000000000000)\n2 Built-in Types, Exceptions and Functions (node3.html#SECTION00300000000000000000)\n- 2.1 Built-in Types (node4.html#SECTION00310000000000000000)\n- 2.1.1 Truth Value Testing (node5.html#SECTION00311000000000000000)\n2.1.2 Boolean Operations (node6.html#SECTION00312000000000000000)\n2.1.3 Comparisons (node7.html#SECTION00313000000000000000)\n2.1.4 Numeric Types (node8.html#SECTION00314000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION00314100000000000000)\n2.1.5 Sequence Types (node10.html#SECTION00315000000000000000)\n- More String Operations (node11.html#SECTION00315100000000000000)\nMutable Sequence Types (node12.html#SECTION00315200000000000000)\n2.1.6 Mapping Types (node13.html#SECTION00316000000000000000)\n2.1.7 Other Built-in Types (node14.html#SECTION00317000000000000000)\n- Modules (node15.html#SECTION00317100000000000000)\nClasses and Class Instances (node16.html#SECTION00317200000000000000)\nFunctions (node17.html#SECTION00317300000000000000)\nMethods (node18.html#SECTION00317400000000000000)\nCode Objects (node19.html#SECTION00317500000000000000)\nType Objects (node20.html#SECTION00317600000000000000)\nThe Null Object (node21.html#SECTION00317700000000000000)\nFile Objects (node22.html#SECTION00317800000000000000)\nInternal Objects (node23.html#SECTION00317900000000000000)\n2.1.8 Special Attributes (node24.html#SECTION00318000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION00320000000000000000)\n2.3 Built-in Functions (node26.html#SECTION00330000000000000000)\n3 Python Services (node27.html#SECTION00400000000000000000)\n- 3.1 Built-in Module `sys` (node28.html#SECTION00410000000000000000)\n3.2 Standard Module `types` (node29.html#SECTION00420000000000000000)\n3.3 Standard Module `traceback` (node30.html#SECTION00430000000000000000)\n3.4 Standard Module `pickle` (node31.html#SECTION00440000000000000000)\n3.5 Standard Module `shelve` (node32.html#SECTION00450000000000000000)\n3.6 Standard Module `copy` (node33.html#SECTION00460000000000000000)\n3.7 Built-in Module `marshal` (node34.html#SECTION00470000000000000000)\n3.8 Built-in Module `imp` (node35.html#SECTION00480000000000000000)\n- 3.8.1 Examples (node36.html#SECTION00481000000000000000)\n3.9 Built-in Module `parser` (node37.html#SECTION00490000000000000000)\n- 3.9.1 Creating AST Objects (node38.html#SECTION00491000000000000000)\n3.9.2 Converting AST Objects (node39.html#SECTION00492000000000000000)\n3.9.3 Queries on AST Objects (node40.html#SECTION00493000000000000000)\n3.9.4 Exceptions and Error Handling (node41.html#SECTION00494000000000000000)\n3.9.5 AST Objects (node42.html#SECTION00495000000000000000)\n3.9.6 Examples (node43.html#SECTION00496000000000000000)\n- Emulation of `compile()` (node44.html#SECTION00496100000000000000)\nInformation Discovery (node45.html#SECTION00496200000000000000)\n3.10 Built-in Module `__builtin__` (node46.html#SECTION004100000000000000000)\n3.11 Built-in Module `__main__` (node47.html#SECTION004110000000000000000)\n4 String Services (node48.html#SECTION00500000000000000000)\n- 4.1 Standard Module `string` (node49.html#SECTION00510000000000000000)\n4.2 Built-in Module `regex` (node50.html#SECTION00520000000000000000)\n- 4.2.1 Regular Expressions (node51.html#SECTION00521000000000000000)\n4.2.2 Module Contents (node52.html#SECTION00522000000000000000)\n4.3 Standard Module `regsub` (node53.html#SECTION00530000000000000000)\n4.4 Built-in Module `struct` (node54.html#SECTION00540000000000000000)\n5 Miscellaneous Services (node55.html#SECTION00600000000000000000)\n- 5.1 Built-in Module `math` (node56.html#SECTION00610000000000000000)\n5.2 Standard Module `rand` (node57.html#SECTION00620000000000000000)\n5.3 Standard Module `whrandom` (node58.html#SECTION00630000000000000000)\n5.4 Built-in Module `array` (node59.html#SECTION00640000000000000000)\n6 Generic Operating System Services (node60.html#SECTION00700000000000000000)\n- 6.1 Standard Module `os` (node61.html#SECTION00710000000000000000)\n6.2 Built-in Module `time` (node62.html#SECTION00720000000000000000)\n6.3 Standard Module `getopt` (node63.html#SECTION00730000000000000000)\n6.4 Standard Module `tempfile` (node64.html#SECTION00740000000000000000)\n6.5 Standard Module `errno` (node65.html#SECTION00750000000000000000)\n7 Optional Operating System Services (node66.html#SECTION00800000000000000000)\n- 7.1 Built-in Module `signal` (node67.html#SECTION00810000000000000000)\n7.2 Built-in Module `socket` (node68.html#SECTION00820000000000000000)\n- 7.2.1 Socket Objects (node69.html#SECTION00821000000000000000)\n7.2.2 Example (node70.html#SECTION00822000000000000000)\n7.3 Built-in Module `select` (node71.html#SECTION00830000000000000000)\n7.4 Built-in Module `thread` (node72.html#SECTION00840000000000000000)\n8 UNIX Specific Services (node73.html#SECTION00900000000000000000)\n- 8.1 Built-in Module `posix` (node74.html#SECTION00910000000000000000)\n8.2 Standard Module `posixpath` (node75.html#SECTION00920000000000000000)\n8.3 Built-in Module `pwd` (node76.html#SECTION00930000000000000000)\n8.4 Built-in Module `grp` (node77.html#SECTION00940000000000000000)\n8.5 Built-in module crypt (node78.html#SECTION00950000000000000000)\n8.6 Built-in Module `dbm` (node79.html#SECTION00960000000000000000)\n8.7 Built-in Module `gdbm` (node80.html#SECTION00970000000000000000)\n8.8 Built-in Module `termios` (node81.html#SECTION00980000000000000000)\n- 8.8.1 Example (node82.html#SECTION00981000000000000000)\n8.9 Standard Module `TERMIOS` (node83.html#SECTION00990000000000000000)\n8.10 Built-in Module `fcntl` (node84.html#SECTION009100000000000000000)\n8.11 Standard Module `posixfile` (node85.html#SECTION009110000000000000000)\n8.12 Built-in Module `syslog` (node86.html#SECTION009120000000000000000)\n9 The Python Debugger (node87.html#SECTION001000000000000000000)\n- 9.1 Debugger Commands (node88.html#SECTION001010000000000000000)\n9.2 How It Works (node89.html#SECTION001020000000000000000)\n10 The Python Profiler (node90.html#SECTION001100000000000000000)\n- 10.1 Introduction to the profiler (node91.html#SECTION001110000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node92.html#SECTION001120000000000000000)\n10.3 Instant Users Manual (node93.html#SECTION001130000000000000000)\n10.4 What Is Deterministic Profiling? (node94.html#SECTION001140000000000000000)\n10.5 Reference Manual (node95.html#SECTION001150000000000000000)\n- 10.5.1 The `Stats` Class (node96.html#SECTION001151000000000000000)\n10.6 Limitations (node97.html#SECTION001160000000000000000)\n10.7 Calibration (node98.html#SECTION001170000000000000000)\n10.8 Extensions - Deriving Better Profilers (node99.html#SECTION001180000000000000000)\n- 10.8.1 OldProfile Class (node100.html#SECTION001181000000000000000)\n10.8.2 HotProfile Class (node101.html#SECTION001182000000000000000)\n11 Internet and WWW Services (node102.html#SECTION001200000000000000000)\n- 11.1 Standard Module `cgi` (node103.html#SECTION001210000000000000000)\n- 11.1.1 Introduction (node104.html#SECTION001211000000000000000)\n11.1.2 Using the cgi module (node105.html#SECTION001212000000000000000)\n11.1.3 Old classes (node106.html#SECTION001213000000000000000)\n11.1.4 Functions (node107.html#SECTION001214000000000000000)\n11.1.5 Caring about security (node108.html#SECTION001215000000000000000)\n11.1.6 Installing your CGI script on a Unix system (node109.html#SECTION001216000000000000000)\n11.1.7 Testing your CGI script (node110.html#SECTION001217000000000000000)\n11.1.8 Debugging CGI scripts (node111.html#SECTION001218000000000000000)\n11.1.9 Common problems and solutions (node112.html#SECTION001219000000000000000)\n11.2 Standard Module `urllib` (node113.html#SECTION001220000000000000000)\n11.3 Standard Module `httplib` (node114.html#SECTION001230000000000000000)\n- 11.3.1 HTTP Objects (node115.html#SECTION001231000000000000000)\n11.3.2 Example (node116.html#SECTION001232000000000000000)\n11.4 Standard Module `ftplib` (node117.html#SECTION001240000000000000000)\n- 11.4.1 FTP Objects (node118.html#SECTION001241000000000000000)\n11.5 Standard Module `gopherlib` (node119.html#SECTION001250000000000000000)\n11.6 Standard Module `nntplib` (node120.html#SECTION001260000000000000000)\n- 11.6.1 NNTP Objects (node121.html#SECTION001261000000000000000)\n11.7 Standard Module `urlparse` (node122.html#SECTION001270000000000000000)\n11.8 Standard Module `sgmllib` (node123.html#SECTION001280000000000000000)\n11.9 Standard Module `htmllib` (node124.html#SECTION001290000000000000000)\n11.10 Standard Module `formatter` (node125.html#SECTION0012100000000000000000)\n- 11.10.1 The Formatter Interface (node126.html#SECTION0012101000000000000000)\n11.10.2 Formatter Implementations (node127.html#SECTION0012102000000000000000)\n11.10.3 The Writer Interface (node128.html#SECTION0012103000000000000000)\n11.10.4 Writer Implementations (node129.html#SECTION0012104000000000000000)\n11.11 Standard Module `rfc822` (node130.html#SECTION0012110000000000000000)\n- 11.11.1 Message Objects (node131.html#SECTION0012111000000000000000)\n11.12 Standard Module `mimetools` (node132.html#SECTION0012120000000000000000)\n- 11.12.1 Additional Methods of Message objects (node133.html#SECTION0012121000000000000000)\n11.13 Standard module `binhex` (node134.html#SECTION0012130000000000000000)\n- 11.13.1 notes (node135.html#SECTION0012131000000000000000)\n11.14 Standard module `uu` (node136.html#SECTION0012140000000000000000)\n11.15 Built-in Module `binascii` (node137.html#SECTION0012150000000000000000)\n11.16 Standard module `xdrlib` (node138.html#SECTION0012160000000000000000)\n- 11.16.1 Packer Objects (node139.html#SECTION0012161000000000000000)\n11.16.2 Unpacker Objects (node140.html#SECTION0012162000000000000000)\n11.16.3 Exceptions (node141.html#SECTION0012163000000000000000)\n11.16.4 Supporting Floating Point Data (node142.html#SECTION0012164000000000000000)\n12 Restricted Execution (node143.html#SECTION001300000000000000000)\n- 12.1 Standard Module `rexec` (node144.html#SECTION001310000000000000000)\n- 12.1.1 An example (node145.html#SECTION001311000000000000000)\n12.2 Standard Module `Bastion` (node146.html#SECTION001320000000000000000)\n13 Multimedia Services (node147.html#SECTION001400000000000000000)\n- 13.1 Built-in Module `audioop` (node148.html#SECTION001410000000000000000)\n13.2 Built-in Module `imageop` (node149.html#SECTION001420000000000000000)\n13.3 Standard Module `aifc` (node150.html#SECTION001430000000000000000)\n13.4 Built-in Module `jpeg` (node151.html#SECTION001440000000000000000)\n13.5 Built-in Module `rgbimg` (node152.html#SECTION001450000000000000000)\n13.6 Standard module `imghdr` (node153.html#SECTION001460000000000000000)\n14 Cryptographic Services (node154.html#SECTION001500000000000000000)\n- 14.1 Built-in Module `md5` (node155.html#SECTION001510000000000000000)\n14.2 Built-in Module `mpz` (node156.html#SECTION001520000000000000000)\n14.3 Built-in Module `rotor` (node157.html#SECTION001530000000000000000)\n15 Macintosh Specific Services (node158.html#SECTION001600000000000000000)\n- 15.1 Built-in Module `mac` (node159.html#SECTION001610000000000000000)\n15.2 Standard Module `macpath` (node160.html#SECTION001620000000000000000)\n15.3 Built-in Module `ctb` (node161.html#SECTION001630000000000000000)\n- 15.3.1 connection object (node162.html#SECTION001631000000000000000)\n15.4 Built-in Module `macconsole` (node163.html#SECTION001640000000000000000)\n- 15.4.1 macconsole options object (node164.html#SECTION001641000000000000000)\n15.4.2 console window object (node165.html#SECTION001642000000000000000)\n15.5 Built-in Module `macdnr` (node166.html#SECTION001650000000000000000)\n- 15.5.1 dnr result object (node167.html#SECTION001651000000000000000)\n15.6 Built-in Module `macfs` (node168.html#SECTION001660000000000000000)\n- 15.6.1 FSSpec objects (node169.html#SECTION001661000000000000000)\n15.6.2 alias objects (node170.html#SECTION001662000000000000000)\n15.6.3 FInfo objects (node171.html#SECTION001663000000000000000)\n15.7 Built-in Module `MacOS` (node172.html#SECTION001670000000000000000)\n15.8 Standard module `macostools` (node173.html#SECTION001680000000000000000)\n15.9 Standard module `findertools` (node174.html#SECTION001690000000000000000)\n15.10 Built-in Module `mactcp` (node175.html#SECTION0016100000000000000000)\n- 15.10.1 TCP Stream Objects (node176.html#SECTION0016101000000000000000)\n15.10.2 TCP Status Objects (node177.html#SECTION0016102000000000000000)\n15.10.3 UDP Stream Objects (node178.html#SECTION0016103000000000000000)\n15.11 Built-in Module `macspeech` (node179.html#SECTION0016110000000000000000)\n- 15.11.1 voice objects (node180.html#SECTION0016111000000000000000)\n15.11.2 speech channel objects (node181.html#SECTION0016112000000000000000)\n15.12 Standard module `EasyDialogs` (node182.html#SECTION0016120000000000000000)\n15.13 Standard module `FrameWork` (node183.html#SECTION0016130000000000000000)\n- 15.13.1 Application objects (node184.html#SECTION0016131000000000000000)\n15.13.2 Window Objects (node185.html#SECTION0016132000000000000000)\n15.13.3 ControlsWindow Object (node186.html#SECTION0016133000000000000000)\n15.13.4 ScrolledWindow Object (node187.html#SECTION0016134000000000000000)\n15.13.5 DialogWindow Objects (node188.html#SECTION0016135000000000000000)\n15.14 Standard module `MiniAEFrame` (node189.html#SECTION0016140000000000000000)\n- 15.14.1 AEServer Objects (node190.html#SECTION0016141000000000000000)\n16 Standard Windowing Interface (node191.html#SECTION001700000000000000000)\n- 16.1 Built-in Module `stdwin` (node192.html#SECTION001710000000000000000)\n- 16.1.1 Functions Defined in Module `stdwin` (node193.html#SECTION001711000000000000000)\n16.1.2 Window Objects (node194.html#SECTION001712000000000000000)\n16.1.3 Drawing Objects (node195.html#SECTION001713000000000000000)\n16.1.4 Menu Objects (node196.html#SECTION001714000000000000000)\n16.1.5 Bitmap Objects (node197.html#SECTION001715000000000000000)\n16.1.6 Text-edit Objects (node198.html#SECTION001716000000000000000)\n16.1.7 Example (node199.html#SECTION001717000000000000000)\n16.2 Standard Module `stdwinevents` (node200.html#SECTION001720000000000000000)\n16.3 Standard Module `rect` (node201.html#SECTION001730000000000000000)\n17 SGI IRIX Specific Services (node202.html#SECTION001800000000000000000)\n- 17.1 Built-in Module `al` (node203.html#SECTION001810000000000000000)\n- 17.1.1 Configuration Objects (node204.html#SECTION001811000000000000000)\n17.1.2 Port Objects (node205.html#SECTION001812000000000000000)\n17.2 Standard Module `AL` (node206.html#SECTION001820000000000000000)\n17.3 Built-in Module `cd` (node207.html#SECTION001830000000000000000)\n17.4 Built-in Module `fl` (node208.html#SECTION001840000000000000000)\n- 17.4.1 Functions Defined in Module `fl` (node209.html#SECTION001841000000000000000)\n17.4.2 Form Objects (node210.html#SECTION001842000000000000000)\n17.4.3 FORMS Objects (node211.html#SECTION001843000000000000000)\n17.5 Standard Module `FL` (node212.html#SECTION001850000000000000000)\n17.6 Standard Module `flp` (node213.html#SECTION001860000000000000000)\n17.7 Built-in Module `fm` (node214.html#SECTION001870000000000000000)\n17.8 Built-in Module `gl` (node215.html#SECTION001880000000000000000)\n17.9 Standard Modules `GL` and `DEVICE` (node216.html#SECTION001890000000000000000)\n17.10 Built-in Module `imgfile` (node217.html#SECTION0018100000000000000000)\n18 SunOS Specific Services (node218.html#SECTION001900000000000000000)\n- 18.1 Built-in Module `sunaudiodev` (node219.html#SECTION001910000000000000000)\n- 18.1.1 Audio Device Objects (node220.html#SECTION001911000000000000000)\nIndex (node221.html#SECTION002000000000000000000)\nAbout this document ... (node222.html#SECTION002100000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 15715, "url": "https://docs.python.org/{python_version}/lib/node1.html"} {"title": "2.1.5 Sequence Types", "text": "node11.html node4.html node9.html node1.html node221.html\n---\n## 2.1.5 Sequence Types\nThere are three sequence types: strings, lists and tuples.\nStrings literals are written in single or double quotes:\n`'xyzzy'`, `\"frobozz\"`. See Chapter 2 of the 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.,\n`a, 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#385\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:\n,\nNotes:\n---\n- More String Operations (node11.html#SECTION00315100000000000000)\nMutable Sequence Types (node12.html#SECTION00315200000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1266, "url": "https://docs.python.org/{python_version}/lib/node10.html"} {"title": "10.8.1 OldProfile Class", "text": "node101.html node99.html node99.html node1.html node221.html\n---\n## 10.8.1 OldProfile Class\nThe following derived profiler simulates the old style profiler,\nproviding errant results on recursive functions. The reason for the\nusefulness of this profiler is that it runs faster (i.e., less\noverhead) than the old profiler. It still creates all the caller\nstats, and is quite useful when there is no recursion in the\nuser's code. It is also a lot more accurate than the old profiler, as\nit does not charge all its overhead time to the user's code.\n```text\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@cnri.reston.va.us", "python_version": "1.4", "length": 1774, "url": "https://docs.python.org/{python_version}/lib/node100.html"} {"title": "10.8.2 HotProfile Class", "text": "node102.html node99.html node100.html node1.html node221.html\n---\n## 10.8.2 HotProfile Class\nThis profiler is the fastest derived profile example. It does not\ncalculate caller-callee relationships, and does not calculate\ncumulative time under a function. It only calculates time spent in a\nfunction, so it runs very quickly (re: very low overhead). In truth,\nthe basic profiler is so fast, that is probably not worth the savings\nto give up the data, but this class still provides a nice example.\n```text\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@cnri.reston.va.us", "python_version": "1.4", "length": 1314, "url": "https://docs.python.org/{python_version}/lib/node101.html"} {"title": "11 Internet and WWW Services", "text": "node103.html lib.html node101.html node1.html node221.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\n`sockets`, which is currently only fully supported on Unix and\nWindows NT. Here is an overview:\n---\n- 11.1 Standard Module `cgi` (node103.html#SECTION001210000000000000000)\n- 11.1.1 Introduction (node104.html#SECTION001211000000000000000)\n11.1.2 Using the cgi module (node105.html#SECTION001212000000000000000)\n11.1.3 Old classes (node106.html#SECTION001213000000000000000)\n11.1.4 Functions (node107.html#SECTION001214000000000000000)\n11.1.5 Caring about security (node108.html#SECTION001215000000000000000)\n11.1.6 Installing your CGI script on a Unix system (node109.html#SECTION001216000000000000000)\n11.1.7 Testing your CGI script (node110.html#SECTION001217000000000000000)\n11.1.8 Debugging CGI scripts (node111.html#SECTION001218000000000000000)\n11.1.9 Common problems and solutions (node112.html#SECTION001219000000000000000)\n11.2 Standard Module `urllib` (node113.html#SECTION001220000000000000000)\n11.3 Standard Module `httplib` (node114.html#SECTION001230000000000000000)\n- 11.3.1 HTTP Objects (node115.html#SECTION001231000000000000000)\n11.3.2 Example (node116.html#SECTION001232000000000000000)\n11.4 Standard Module `ftplib` (node117.html#SECTION001240000000000000000)\n- 11.4.1 FTP Objects (node118.html#SECTION001241000000000000000)\n11.5 Standard Module `gopherlib` (node119.html#SECTION001250000000000000000)\n11.6 Standard Module `nntplib` (node120.html#SECTION001260000000000000000)\n- 11.6.1 NNTP Objects (node121.html#SECTION001261000000000000000)\n11.7 Standard Module `urlparse` (node122.html#SECTION001270000000000000000)\n11.8 Standard Module `sgmllib` (node123.html#SECTION001280000000000000000)\n11.9 Standard Module `htmllib` (node124.html#SECTION001290000000000000000)\n11.10 Standard Module `formatter` (node125.html#SECTION0012100000000000000000)\n- 11.10.1 The Formatter Interface (node126.html#SECTION0012101000000000000000)\n11.10.2 Formatter Implementations (node127.html#SECTION0012102000000000000000)\n11.10.3 The Writer Interface (node128.html#SECTION0012103000000000000000)\n11.10.4 Writer Implementations (node129.html#SECTION0012104000000000000000)\n11.11 Standard Module `rfc822` (node130.html#SECTION0012110000000000000000)\n- 11.11.1 Message Objects (node131.html#SECTION0012111000000000000000)\n11.12 Standard Module `mimetools` (node132.html#SECTION0012120000000000000000)\n- 11.12.1 Additional Methods of Message objects (node133.html#SECTION0012121000000000000000)\n11.13 Standard module `binhex` (node134.html#SECTION0012130000000000000000)\n- 11.13.1 notes (node135.html#SECTION0012131000000000000000)\n11.14 Standard module `uu` (node136.html#SECTION0012140000000000000000)\n11.15 Built-in Module `binascii` (node137.html#SECTION0012150000000000000000)\n11.16 Standard module `xdrlib` (node138.html#SECTION0012160000000000000000)\n- 11.16.1 Packer Objects (node139.html#SECTION0012161000000000000000)\n11.16.2 Unpacker Objects (node140.html#SECTION0012162000000000000000)\n11.16.3 Exceptions (node141.html#SECTION0012163000000000000000)\n11.16.4 Supporting Floating Point Data (node142.html#SECTION0012164000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3434, "url": "https://docs.python.org/{python_version}/lib/node102.html"} {"title": "11.1 Standard Module cgi", "text": "node104.html node102.html node102.html node1.html node221.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- 11.1.1 Introduction (node104.html#SECTION001211000000000000000)\n11.1.2 Using the cgi module (node105.html#SECTION001212000000000000000)\n11.1.3 Old classes (node106.html#SECTION001213000000000000000)\n11.1.4 Functions (node107.html#SECTION001214000000000000000)\n11.1.5 Caring about security (node108.html#SECTION001215000000000000000)\n11.1.6 Installing your CGI script on a Unix system (node109.html#SECTION001216000000000000000)\n11.1.7 Testing your CGI script (node110.html#SECTION001217000000000000000)\n11.1.8 Debugging CGI scripts (node111.html#SECTION001218000000000000000)\n11.1.9 Common problems and solutions (node112.html#SECTION001219000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 929, "url": "https://docs.python.org/{python_version}/lib/node103.html"} {"title": "11.1.1 Introduction", "text": "node105.html node103.html node103.html node1.html node221.html\n---\n## 11.1.1 Introduction\nA CGI script is invoked by an HTTP server, usually to process user\ninput submitted through an HTML `
` or `` element.\nMost often, CGI scripts live in the server's special `cgi-bin`\ndirectory. The HTTP server places all sorts of information about the\nrequest (such as the client's hostname, the requested URL, the query\nstring, and lots of other goodies) in the script's shell environment,\nexecutes the script, and sends the script's output back to the client.\nThe script's input is connected to the client too, and sometimes the\nform data is read this way; at other times the form data is passed via\nthe ``query string'' part of the URL. This module (`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@cnri.reston.va.us", "python_version": "1.4", "length": 1863, "url": "https://docs.python.org/{python_version}/lib/node104.html"} {"title": "11.1.2 Using the cgi module", "text": "node106.html node103.html node104.html node1.html node221.html\n---\n## 11.1.2 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\n`Content-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---\nnode106.html node103.html node104.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3585, "url": "https://docs.python.org/{python_version}/lib/node105.html"} {"title": "11.1.3 Old classes", "text": "node107.html node103.html node105.html node1.html node221.html\n---\n## 11.1.3 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.\n`SvFormContentDict`: single value form content as dictionary; assumes each\nfield name occurs in the form only once.\n`FormContentDict`: multiple 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@cnri.reston.va.us", "python_version": "1.4", "length": 815, "url": "https://docs.python.org/{python_version}/lib/node106.html"} {"title": "11.1.4 Functions", "text": "node108.html node103.html node106.html node1.html node221.html\n---\n## 11.1.4 Functions\nThese are useful if you want more control, or if you want to employ\nsome of the algorithms implemented in this module in other\ncircumstances.\n---\nnode108.html node103.html node106.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 319, "url": "https://docs.python.org/{python_version}/lib/node107.html"} {"title": "11.1.5 Caring about security", "text": "node109.html node103.html node107.html node1.html node221.html\n---\n## 11.1.5 Caring about security\nThere's one important rule: if you invoke an external program (e.g.\nvia the `os.system()` or `os.popen()` functions), 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@cnri.reston.va.us", "python_version": "1.4", "length": 784, "url": "https://docs.python.org/{python_version}/lib/node108.html"} {"title": "11.1.6 Installing your CGI script on a Unix system", "text": "node110.html node103.html node108.html node1.html node221.html\n---\n## 11.1.6 Installing your CGI script on a Unix system\nRead the documentation for your HTTP server and check with your local\nsystem administrator to find the directory where CGI scripts should be\ninstalled; usually this is in a directory `cgi-bin` in the server tree.\nMake sure that your script is readable and executable by ``others''; the\nUnix file mode should be 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@cnri.reston.va.us", "python_version": "1.4", "length": 1970, "url": "https://docs.python.org/{python_version}/lib/node109.html"} {"title": "More String Operations", "text": "node12.html node10.html node10.html node1.html node221.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 right argument, and\nreturns the string resulting from this formatting operation.\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#491\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#500\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\n`string` and in built-in module `regex`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2008, "url": "https://docs.python.org/{python_version}/lib/node11.html"} {"title": "11.1.7 Testing your CGI script", "text": "node111.html node103.html node109.html node1.html node221.html\n---\n## 11.1.7 Testing your CGI script\nUnfortunately, a CGI script will generally not run when you try it\nfrom the command line, and a script that works perfectly from the\ncommand line may fail mysteriously when run from the server. There's\none reason why you should still test your script from the command\nline: if it contains a syntax error, the python interpreter won't\nexecute it at all, and the HTTP server will most likely send a cryptic\nerror to the client.\nAssuming your script has no syntax errors, yet it does not work, you\nhave no choice but to read the next section:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 668, "url": "https://docs.python.org/{python_version}/lib/node110.html"} {"title": "11.1.8 Debugging CGI scripts", "text": "node112.html node103.html node110.html node1.html node221.html\n---\n## 11.1.8 Debugging CGI scripts\nFirst of all, check for trivial installation errors - reading the\nsection above on installing your CGI script carefully can save you a\nlot of time. If you wonder whether you have understood the\ninstallation procedure correctly, try installing a copy of this module\nfile (`cgi.py`) as a CGI script. When invoked as a script, the file\nwill dump its environment and the contents of the form in HTML form.\nGive it the right mode etc, and send it a request. If it's installed\nin the standard `cgi-bin` directory, it should be possible to send it a\nrequest by entering a URL into your browser of the form:\n```text\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() function from\nyour script: replace its main code with the single statement\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.stdout`Wrap 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`. The `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---\nnode112.html node103.html node110.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3617, "url": "https://docs.python.org/{python_version}/lib/node111.html"}
{"title": "11.1.9 Common problems and solutions", "text": "node113.html node103.html node111.html node1.html node221.html\n---\n## 11.1.9 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\n`import 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@cnri.reston.va.us", "python_version": "1.4", "length": 1061, "url": "https://docs.python.org/{python_version}/lib/node112.html"}
{"title": "11.2 Standard Module urllib", "text": "node114.html node102.html node112.html node1.html node221.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\n`htmllib` 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---\nnode114.html node102.html node112.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2026, "url": "https://docs.python.org/{python_version}/lib/node113.html"}
{"title": "11.3 Standard Module httplib", "text": "node115.html node102.html node113.html node1.html node221.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\n`urllib` 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- 11.3.1 HTTP Objects (node115.html#SECTION001231000000000000000)\n11.3.2 Example (node116.html#SECTION001232000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1189, "url": "https://docs.python.org/{python_version}/lib/node114.html"}
{"title": "11.3.1 HTTP Objects", "text": "node116.html node114.html node114.html node1.html node221.html\n---\n## 11.3.1 HTTP Objects\n`HTTP` instances have the following methods:\n---\nnode116.html node114.html node114.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 225, "url": "https://docs.python.org/{python_version}/lib/node115.html"}
{"title": "11.3.2 Example", "text": "node117.html node114.html node115.html node1.html node221.html\n---\n## 11.3.2 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@cnri.reston.va.us", "python_version": "1.4", "length": 496, "url": "https://docs.python.org/{python_version}/lib/node116.html"}
{"title": "11.4 Standard Module ftplib", "text": "node118.html node102.html node116.html node1.html node221.html\n---\n# 11.4 Standard Module `ftplib`\nThis module defines the class `FTP` and a few related items. The\n`FTP` 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\n959.\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- 11.4.1 FTP Objects (node118.html#SECTION001241000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1073, "url": "https://docs.python.org/{python_version}/lib/node117.html"}
{"title": "11.4.1 FTP Objects", "text": "node119.html node117.html node117.html node1.html node221.html\n---\n## 11.4.1 FTP Objects\nFTP instances have the following methods:\n---\nnode119.html node117.html node117.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 221, "url": "https://docs.python.org/{python_version}/lib/node118.html"}
{"title": "11.5 Standard Module gopherlib", "text": "node120.html node102.html node118.html node1.html node221.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 charactger\nof the selector is `1') are transferred using the same protocol.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 796, "url": "https://docs.python.org/{python_version}/lib/node119.html"}
{"title": "Mutable Sequence Types", "text": "node13.html node10.html node11.html node1.html node221.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):\n,\nNotes:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 519, "url": "https://docs.python.org/{python_version}/lib/node12.html"}
{"title": "11.6 Standard Module nntplib", "text": "node121.html node102.html node119.html node1.html node221.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- 11.6.1 NNTP Objects (node121.html#SECTION001261000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1748, "url": "https://docs.python.org/{python_version}/lib/node120.html"}
{"title": "11.6.1 NNTP Objects", "text": "node122.html node120.html node120.html node1.html node221.html\n---\n## 11.6.1 NNTP Objects\nNNTP instances have the following methods. The response that is\nreturned as the first item in the return tuple of almost all methods\nis the server's response: a string beginning with a three-digit code.\nIf the server's response indicates an error, the method raises one of\nthe above exceptions.\n---\nnode122.html node120.html node120.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 475, "url": "https://docs.python.org/{python_version}/lib/node121.html"}
{"title": "11.7 Standard Module urlparse", "text": "node123.html node102.html node121.html node1.html node221.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 current Internet draft on\nRelative Uniform Resource Locators (and discovered a bug in an earlier\ndraft!).\nIt defines the following functions:\n---\nnode123.html node102.html node121.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 628, "url": "https://docs.python.org/{python_version}/lib/node122.html"}
{"title": "11.8 Standard Module sgmllib", "text": "node124.html node102.html node122.html node1.html node221.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```< tag attr =\" value \" ...>`'' 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 ```-`''.\n\nThe `SGMLParser` class must be instantiated without arguments.\nIt has the following interface methods:\n\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:\n\nNote that the parser maintains a stack of open elements for which no\nend tag has been found yet. Only tags processed by\n`start_ tag ()` are pushed on this stack. Definition of an\n`end_ tag ()` method is optional for these tags. For tags\nprocessed by `do_ tag ()` or by `unknown_tag()`, no\n`end_ 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\n---\n\nnode124.html node102.html node122.html node1.html node221.html\n\nNext: 11.9 Standard Module htmllib (node124.html)\nUp: 11 Internet and WWW (node102.html)\nPrevious: 11.7 Standard Module urlparse (node122.html)\n\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1948, "url": "https://docs.python.org/{python_version}/lib/node123.html"}
{"title": "11.9 Standard Module htmllib", "text": "node125.html node102.html node123.html node1.html node221.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\n`HTMLParser` 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\n`sgmllib`. Two implementations of formatter objects are\nprovided in the `formatter` module; refer to the documentation\nfor that module for information on the formatter interface.\nThe following is a summary of the interface defined by\n`sgmllib.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 ()`,\n`end_ tag ()`, or `do_ tag ()`. The parser will\ncall these at appropriate moments: `start_ tag` or\n`do_ tag` is called when an opening tag of the form\n`< tag ...>` is encountered; `end_ tag` is called\nwhen a closing tag of the form `< tag >` is encountered. If\nan opening tag requires a corresponding closing tag, like `

`\n... `

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

`, the class\nshould define the `do_ tag` method.\nThe module defines a single class:\nIn addition to tag methods, the `HTMLParser` class provides some\nadditional methods and instance variables for use within tag methods.\n---\nnode125.html node102.html node123.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2353, "url": "https://docs.python.org/{python_version}/lib/node124.html"} {"title": "11.10 Standard Module formatter", "text": "node126.html node102.html node124.html node1.html node221.html\n---\n# 11.10 Standard Module `formatter`\nThis module supports two interface definitions, each with mulitple\nimplementations. The formatter interface is used by the\n`HTMLParser` 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- 11.10.1 The Formatter Interface (node126.html#SECTION0012101000000000000000)\n11.10.2 Formatter Implementations (node127.html#SECTION0012102000000000000000)\n11.10.3 The Writer Interface (node128.html#SECTION0012103000000000000000)\n11.10.4 Writer Implementations (node129.html#SECTION0012104000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1677, "url": "https://docs.python.org/{python_version}/lib/node125.html"} {"title": "11.10.1 The Formatter Interface", "text": "node127.html node125.html node125.html node1.html node221.html\n---\n## 11.10.1 The Formatter Interface\nInterfaces to create formatters are dependent on the specific\nformatter class being instantiated. The interfaces described below\nare the required interfaces which all formatters must support once\ninitialized.\nOne data element is defined at the module level:\nThe following attributes are defined for formatter instance objects:\n---\nnode127.html node125.html node125.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 519, "url": "https://docs.python.org/{python_version}/lib/node126.html"} {"title": "11.10.2 Formatter Implementations", "text": "node128.html node125.html node126.html node1.html node221.html\n---\n## 11.10.2 Formatter Implementations\nTwo implementations of formatter objects are provided by this module.\nMost applications may use one of these classes without modification or\nsubclassing.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 285, "url": "https://docs.python.org/{python_version}/lib/node127.html"} {"title": "11.10.3 The Writer Interface", "text": "node129.html node125.html node127.html node1.html node221.html\n---\n## 11.10.3 The Writer Interface\nInterfaces to create writers are dependent on the specific writer\nclass being instantiated. The interfaces described below are the\nrequired interfaces which all writers must support once initialized.\nNote that while most applications can use the `AbstractFormatter`\nclass as a formatter, the writer must typically be provided by the\napplication.\n---\nnode129.html node125.html node127.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 535, "url": "https://docs.python.org/{python_version}/lib/node128.html"} {"title": "11.10.4 Writer Implementations", "text": "node130.html node125.html node128.html node1.html node221.html\n---\n## 11.10.4 Writer Implementations\nThree implementations of the writer object interface are provided as\nexamples by this module. Most applications will need to derive new\nwriter classes from the `NullWriter` class.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 308, "url": "https://docs.python.org/{python_version}/lib/node129.html"} {"title": "2.1.6 Mapping Types", "text": "node14.html node4.html node12.html node1.html node221.html\n---\n## 2.1.6 Mapping Types\nA mapping object maps values of one type (the key type) to\narbitrary objects. Mappings are mutable objects. There is currently\nonly one standard mapping type, the dictionary. A dictionary's keys are\nalmost arbitrary values. The only types of values not acceptable as\nkeys are values containing lists or dictionaries or other mutable\ntypes that are compared by value rather than by object identity.\nNumeric types used for keys obey the normal rules for numeric\ncomparison: if two numbers compare equal (e.g. 1 and 1.0) then they\ncan be used interchangeably to index the same dictionary entry.\nDictionaries are created by placing a comma-separated list of\n`key :, value` pairs within braces, for example:\n`{'jack':,4098, 'sjoerd':,4127}` or\n`{4098:,'jack', 4127:,'sjoerd'}`.\nThe following operations are defined on mappings (where a is a\nmapping, k is a key and x is an arbitrary object):\n,\nNotes:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1009, "url": "https://docs.python.org/{python_version}/lib/node13.html"} {"title": "11.11 Standard Module rfc822", "text": "node131.html node102.html node129.html node1.html node221.html\n---\n# 11.11 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 headers\nfrom a file.\nA `Message` instance is instantiated with an open file object as\nparameter. Instantiation reads headers from the file up to a blank\nline and stores 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- 11.11.1 Message Objects (node131.html#SECTION0012111000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 995, "url": "https://docs.python.org/{python_version}/lib/node130.html"} {"title": "11.11.1 Message Objects", "text": "node132.html node130.html node130.html node1.html node221.html\n---\n## 11.11.1 Message Objects\nA `Message` instance has the following methods:\n`Message` 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()`,\n`m.values()` and `m.items()` act as expected (and\nconsistently).\nFinally, `Message` instances have two public instance variables:\n---\nnode132.html node130.html node130.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 532, "url": "https://docs.python.org/{python_version}/lib/node131.html"} {"title": "11.12 Standard Module mimetools", "text": "node133.html node102.html node131.html node1.html node221.html\n---\n# 11.12 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- 11.12.1 Additional Methods of Message objects (node133.html#SECTION0012121000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 436, "url": "https://docs.python.org/{python_version}/lib/node132.html"} {"title": "11.12.1 Additional Methods of Message objects", "text": "node134.html node132.html node132.html node1.html node221.html\n---\n## 11.12.1 Additional Methods of Message objects\nThe `mimetools.Message` class defines the following methods in\naddition to the `rfc822.Message` class:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 246, "url": "https://docs.python.org/{python_version}/lib/node133.html"} {"title": "11.13 Standard module binhex", "text": "node135.html node102.html node133.html node1.html node221.html\n---\n# 11.13 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- 11.13.1 notes (node135.html#SECTION0012131000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 506, "url": "https://docs.python.org/{python_version}/lib/node134.html"} {"title": "11.13.1 notes", "text": "node136.html node134.html node134.html node1.html node221.html\n---\n## 11.13.1 notes\nThere is an alternative, more powerful interface to the coder and\ndecoder, see the source for details.\nIf you code or decode textfiles on non-Macintosh platforms they will\nstill use the macintosh newline convention (carriage-return as end of\nline).\nAs of this writing, hexbin appears to not work in all cases.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 421, "url": "https://docs.python.org/{python_version}/lib/node135.html"} {"title": "11.14 Standard module uu", "text": "node137.html node102.html node135.html node1.html node221.html\n---\n# 11.14 Standard module `uu`\nThis module encodes and decodes files in uuencode format, allowing\narbitrary binary data to be transferred over ascii-only connections.\nWhereever a file argument is expected, the methods accept either a\npathname (`'-'` for stdin/stdout) or a file-like object.\nNormally you would pass filenames, but there is one case where you\nhave to open the file yourself: if you are on a non-unix platform and\nyour binary file is actually a textfile that you want encoded\nunix-compatible you will have to open the file yourself as a textfile,\nso newline conversion is performed.\nThis code was contributed by Lance Ellinghouse, and modified by Jack\nJansen.\nThe `uu` module defines the following functions:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 815, "url": "https://docs.python.org/{python_version}/lib/node136.html"} {"title": "11.15 Built-in Module binascii", "text": "node138.html node102.html node136.html node1.html node221.html\n---\n# 11.15 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---\nnode138.html node102.html node136.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 568, "url": "https://docs.python.org/{python_version}/lib/node137.html"} {"title": "11.16 Standard module xdrlib", "text": "node139.html node102.html node137.html node1.html node221.html\n---\n# 11.16 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, although some, most notably `float` and `double` are\nonly supported on those operating systems that provide an XDR\nlibrary.\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- 11.16.1 Packer Objects (node139.html#SECTION0012161000000000000000)\n11.16.2 Unpacker Objects (node140.html#SECTION0012162000000000000000)\n11.16.3 Exceptions (node141.html#SECTION0012163000000000000000)\n11.16.4 Supporting Floating Point Data (node142.html#SECTION0012164000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 923, "url": "https://docs.python.org/{python_version}/lib/node138.html"} {"title": "11.16.1 Packer Objects", "text": "node140.html node138.html node138.html node1.html node221.html\n---\n## 11.16.1 Packer Objects\n`Packer` 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`,\n`pack_enum`, `pack_bool`, `pack_uhyper`,\nand `pack_hyper`.\nThe following methods pack floating point numbers, however they\nrequire C library support. Without the optional C built-in module,\nboth of these methods will raise an `xdrlib.ConversionError`\nexception. See the note at the end of this chapter for details.\nThe following methods support packing strings, bytes, and opaque data:\nThe following methods support packing arrays and lists:\n---\nnode140.html node138.html node138.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 997, "url": "https://docs.python.org/{python_version}/lib/node139.html"} {"title": "2.1.7 Other Built-in Types", "text": "node15.html node4.html node13.html node1.html node221.html\n---\n## 2.1.7 Other Built-in Types\nThe interpreter supports several other kinds of objects.\nMost of these support only one or two operations.\n---\n- Modules (node15.html#SECTION00317100000000000000)\nClasses and Class Instances (node16.html#SECTION00317200000000000000)\nFunctions (node17.html#SECTION00317300000000000000)\nMethods (node18.html#SECTION00317400000000000000)\nCode Objects (node19.html#SECTION00317500000000000000)\nType Objects (node20.html#SECTION00317600000000000000)\nThe Null Object (node21.html#SECTION00317700000000000000)\nFile Objects (node22.html#SECTION00317800000000000000)\nInternal Objects (node23.html#SECTION00317900000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 737, "url": "https://docs.python.org/{python_version}/lib/node14.html"} {"title": "11.16.2 Unpacker Objects", "text": "node141.html node138.html node139.html node1.html node221.html\n---\n## 11.16.2 Unpacker Objects\n`Unpacker` 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. The same caveats apply for `unpack_float` and\n`unpack_double` as above.\nIn addition, the following methods unpack strings, bytes, and opaque\ndata:\nThe following methods support unpacking arrays and lists:\n---\nnode141.html node138.html node139.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 718, "url": "https://docs.python.org/{python_version}/lib/node140.html"} {"title": "11.16.3 Exceptions", "text": "node142.html node138.html node140.html node1.html node221.html\n---\n## 11.16.3 Exceptions\nExceptions in this module are coded as class instances:\nHere is an example of how you would catch one of these exceptions:\n```text\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@cnri.reston.va.us", "python_version": "1.4", "length": 400, "url": "https://docs.python.org/{python_version}/lib/node141.html"} {"title": "11.16.4 Supporting Floating Point Data", "text": "node143.html node138.html node141.html node1.html node221.html\n---\n## 11.16.4 Supporting Floating Point Data\nPacking and unpacking floating point data,\ni.e. `Packer.pack_float`, `Packer.pack_double`,\n`Unpacker.unpack_float`, and `Unpacker.unpack_double`, are\nonly supported with the helper built-in `_xdr` module, which\nrelies on your operating system having the appropriate XDR library\nroutines.\nIf you have built the Python interpeter with the `_xdr` module,\nor have built the `_xdr` module as a shared library,\n`xdrlib` will use these to pack and unpack floating point\nnumbers. Otherwise, using these routines will raise a\n`ConversionError` exception.\nSee the Python installation instructions for details on building the\n`_xdr` module.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 766, "url": "https://docs.python.org/{python_version}/lib/node142.html"} {"title": "12 Restricted Execution", "text": "node144.html lib.html node142.html node1.html node221.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\n`open()` function so that it raises an exception whenever the\nmode parameter is `'w'`. It might also perform a\n`chroot()`-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\n`IOError`s 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` (node144.html#SECTION001310000000000000000)\n- 12.1.1 An example (node145.html#SECTION001311000000000000000)\n12.2 Standard Module `Bastion` (node146.html#SECTION001320000000000000000)\n---\nnode144.html lib.html node142.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3748, "url": "https://docs.python.org/{python_version}/lib/node143.html"} {"title": "12.1 Standard Module rexec", "text": "node145.html node143.html node143.html node1.html node221.html\n---\n# 12.1 Standard Module `rexec`\nThis module contains the `RExec` class, which supports\n`r_exec()`, `r_eval()`, `r_execfile()`, and\n`r_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 used by the\n`__init__` method. Changing them on an existing instance won't\nhave any effect; instead, create a subclass of `RExec` and assign\nthem new values in the class definition. Instances of the new class\nwill then use those new values. All these attributes are tuples of\nstrings.\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`,\n`sys.stderr`, and `sys.stdout`.\n`RExec` 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- 12.1.1 An example (node145.html#SECTION001311000000000000000)\n---\nnode145.html node143.html node143.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1835, "url": "https://docs.python.org/{python_version}/lib/node144.html"} {"title": "12.1.1 An example", "text": "node146.html node144.html node144.html node1.html node221.html\n---\n## 12.1.1 An example\nLet us say that we want a slightly more relaxed policy than the\nstandard RExec class. For example, if we're willing to allow files in\n``/tmp`' to be written, we can subclass the `RExec` class:\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\n`r_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@cnri.reston.va.us", "python_version": "1.4", "length": 1339, "url": "https://docs.python.org/{python_version}/lib/node145.html"} {"title": "12.2 Standard Module Bastion", "text": "node147.html node143.html node145.html node1.html node221.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\n`rexec` 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@cnri.reston.va.us", "python_version": "1.4", "length": 554, "url": "https://docs.python.org/{python_version}/lib/node146.html"} {"title": "13 Multimedia Services", "text": "node148.html lib.html node146.html node1.html node221.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` (node148.html#SECTION001410000000000000000)\n13.2 Built-in Module `imageop` (node149.html#SECTION001420000000000000000)\n13.3 Standard Module `aifc` (node150.html#SECTION001430000000000000000)\n13.4 Built-in Module `jpeg` (node151.html#SECTION001440000000000000000)\n13.5 Built-in Module `rgbimg` (node152.html#SECTION001450000000000000000)\n13.6 Standard module `imghdr` (node153.html#SECTION001460000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 774, "url": "https://docs.python.org/{python_version}/lib/node147.html"} {"title": "13.1 Built-in Module audioop", "text": "node149.html node147.html node147.html node1.html node221.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\n`lin2adpcm`) 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---\nnode149.html node147.html node147.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2940, "url": "https://docs.python.org/{python_version}/lib/node148.html"} {"title": "13.2 Built-in Module imageop", "text": "node150.html node147.html node148.html node1.html node221.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---\nnode150.html node147.html node148.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 470, "url": "https://docs.python.org/{python_version}/lib/node149.html"} {"title": "Modules", "text": "node16.html node14.html node14.html node1.html node221.html\n---\n### Modules\nThe only special operation on a module is attribute access:\n`m . 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@cnri.reston.va.us", "python_version": "1.4", "length": 939, "url": "https://docs.python.org/{python_version}/lib/node15.html"} {"title": "13.3 Standard Module aifc", "text": "node151.html node147.html node149.html node1.html node221.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\n`setpos`. In addition the following methods exist. The\n`get` methods can only be called after the corresponding\n`set` methods have been called. Before the first\n`writeframes` or `writeframesraw`, all parameters except for\nthe number of frames must be filled in.\n---\nnode151.html node147.html node149.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1696, "url": "https://docs.python.org/{python_version}/lib/node150.html"} {"title": "13.4 Built-in Module jpeg", "text": "node152.html node147.html node150.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 542, "url": "https://docs.python.org/{python_version}/lib/node151.html"} {"title": "13.5 Built-in Module rgbimg", "text": "node153.html node147.html node151.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 454, "url": "https://docs.python.org/{python_version}/lib/node152.html"} {"title": "13.6 Standard module imghdr", "text": "node154.html node147.html node152.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 526, "url": "https://docs.python.org/{python_version}/lib/node153.html"} {"title": "14 Cryptographic Services", "text": "node155.html lib.html node153.html node1.html node221.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\n``http://www.magnet.com/ amk/python/pct.html`' or send email to\n``amk@magnet.com`' for more information.\n---\n- 14.1 Built-in Module `md5` (node155.html#SECTION001510000000000000000)\n14.2 Built-in Module `mpz` (node156.html#SECTION001520000000000000000)\n14.3 Built-in Module `rotor` (node157.html#SECTION001530000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 955, "url": "https://docs.python.org/{python_version}/lib/node154.html"} {"title": "14.1 Built-in Module md5", "text": "node156.html node154.html node154.html node1.html node221.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\n`update()` 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@cnri.reston.va.us", "python_version": "1.4", "length": 1062, "url": "https://docs.python.org/{python_version}/lib/node155.html"} {"title": "14.2 Built-in Module mpz", "text": "node157.html node154.html node155.html node1.html node221.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\n`abs`, `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:\n`mpz( value )`.\nA number of extra functions are defined in this module. Non\nmpz-arguments are converted to mpz-values first, and the functions\nreturn mpz-numbers.\nAn mpz-number has one method:\n---\nnode157.html node154.html node155.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1356, "url": "https://docs.python.org/{python_version}/lib/node156.html"} {"title": "14.3 Built-in Module rotor", "text": "node158.html node154.html node156.html node1.html node221.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---\nnode158.html node154.html node156.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3029, "url": "https://docs.python.org/{python_version}/lib/node157.html"} {"title": "15 Macintosh Specific Services", "text": "node159.html lib.html node157.html node1.html node221.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:\n`AE` (Apple Events),\n`Cm` (Component Manager),\n`Ctl` (Control Manager),\n`Dlg` (Dialog Manager),\n`Evt` (Event Manager),\n`Fm` (Font Manager),\n`List` (List Manager),\n`Menu` (Moenu Manager),\n`Qd` (QuickDraw),\n`Qt` (QuickTime),\n`Res` (Resource Manager and Handles),\n`Scrap` (Scrap Manager),\n`Snd` (Sound Manager),\n`TE` (TextEdit),\n`Waste` (non-Apple TextEdit replacement) and\n`Win` (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` (node159.html#SECTION001610000000000000000)\n15.2 Standard Module `macpath` (node160.html#SECTION001620000000000000000)\n15.3 Built-in Module `ctb` (node161.html#SECTION001630000000000000000)\n- 15.3.1 connection object (node162.html#SECTION001631000000000000000)\n15.4 Built-in Module `macconsole` (node163.html#SECTION001640000000000000000)\n- 15.4.1 macconsole options object (node164.html#SECTION001641000000000000000)\n15.4.2 console window object (node165.html#SECTION001642000000000000000)\n15.5 Built-in Module `macdnr` (node166.html#SECTION001650000000000000000)\n- 15.5.1 dnr result object (node167.html#SECTION001651000000000000000)\n15.6 Built-in Module `macfs` (node168.html#SECTION001660000000000000000)\n- 15.6.1 FSSpec objects (node169.html#SECTION001661000000000000000)\n15.6.2 alias objects (node170.html#SECTION001662000000000000000)\n15.6.3 FInfo objects (node171.html#SECTION001663000000000000000)\n15.7 Built-in Module `MacOS` (node172.html#SECTION001670000000000000000)\n15.8 Standard module `macostools` (node173.html#SECTION001680000000000000000)\n15.9 Standard module `findertools` (node174.html#SECTION001690000000000000000)\n15.10 Built-in Module `mactcp` (node175.html#SECTION0016100000000000000000)\n- 15.10.1 TCP Stream Objects (node176.html#SECTION0016101000000000000000)\n15.10.2 TCP Status Objects (node177.html#SECTION0016102000000000000000)\n15.10.3 UDP Stream Objects (node178.html#SECTION0016103000000000000000)\n15.11 Built-in Module `macspeech` (node179.html#SECTION0016110000000000000000)\n- 15.11.1 voice objects (node180.html#SECTION0016111000000000000000)\n15.11.2 speech channel objects (node181.html#SECTION0016112000000000000000)\n15.12 Standard module `EasyDialogs` (node182.html#SECTION0016120000000000000000)\n15.13 Standard module `FrameWork` (node183.html#SECTION0016130000000000000000)\n- 15.13.1 Application objects (node184.html#SECTION0016131000000000000000)\n15.13.2 Window Objects (node185.html#SECTION0016132000000000000000)\n15.13.3 ControlsWindow Object (node186.html#SECTION0016133000000000000000)\n15.13.4 ScrolledWindow Object (node187.html#SECTION0016134000000000000000)\n15.13.5 DialogWindow Objects (node188.html#SECTION0016135000000000000000)\n15.14 Standard module `MiniAEFrame` (node189.html#SECTION0016140000000000000000)\n- 15.14.1 AEServer Objects (node190.html#SECTION0016141000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3751, "url": "https://docs.python.org/{python_version}/lib/node158.html"} {"title": "15.1 Built-in Module mac", "text": "node160.html node158.html node158.html node1.html node221.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\n`os`.\nThe following functions are available in this module:\n`chdir`,\n`close`,\n`dup`,\n`fdopen`,\n`getcwd`,\n`lseek`,\n`listdir`,\n`mkdir`,\n`open`,\n`read`,\n`rename`,\n`rmdir`,\n`stat`,\n`sync`,\n`unlink`,\n`write`,\nas well as the exception `error`. Note that the times returned by\n`stat` 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@cnri.reston.va.us", "python_version": "1.4", "length": 866, "url": "https://docs.python.org/{python_version}/lib/node159.html"} {"title": "Classes and Class Instances", "text": "node17.html node14.html node15.html node1.html node221.html\n---\n### Classes and Class Instances\n(See Chapters 3 and 7 of the Python Reference Manual for these.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 188, "url": "https://docs.python.org/{python_version}/lib/node16.html"} {"title": "15.2 Standard Module macpath", "text": "node161.html node158.html node159.html node1.html node221.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\n`os.path`.\nThe following functions are available in this module:\n`normcase`,\n`normpath`,\n`isabs`,\n`join`,\n`split`,\n`isdir`,\n`isfile`,\n`walk`,\n`exists`.\nFor other functions available in `posixpath` dummy counterparts\nare available.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 555, "url": "https://docs.python.org/{python_version}/lib/node160.html"} {"title": "15.3 Built-in Module ctb", "text": "node162.html node158.html node160.html node1.html node221.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- 15.3.1 connection object (node162.html#SECTION001631000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 388, "url": "https://docs.python.org/{python_version}/lib/node161.html"} {"title": "15.3.1 connection object", "text": "node163.html node161.html node161.html node1.html node221.html\n---\n## 15.3.1 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---\nnode163.html node161.html node161.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 318, "url": "https://docs.python.org/{python_version}/lib/node162.html"} {"title": "15.4 Built-in Module macconsole", "text": "node164.html node158.html node162.html node1.html node221.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- 15.4.1 macconsole options object (node164.html#SECTION001641000000000000000)\n15.4.2 console window object (node165.html#SECTION001642000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 489, "url": "https://docs.python.org/{python_version}/lib/node163.html"} {"title": "15.4.1 macconsole options object", "text": "node165.html node163.html node163.html node1.html node221.html\n---\n## 15.4.1 macconsole options object\nThese options are examined when a window is created:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 183, "url": "https://docs.python.org/{python_version}/lib/node164.html"} {"title": "15.4.2 console window object", "text": "node166.html node163.html node164.html node1.html node221.html\n---\n## 15.4.2 console window object\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 126, "url": "https://docs.python.org/{python_version}/lib/node165.html"} {"title": "15.5 Built-in Module macdnr", "text": "node167.html node158.html node165.html node1.html node221.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- 15.5.1 dnr result object (node167.html#SECTION001651000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 471, "url": "https://docs.python.org/{python_version}/lib/node166.html"} {"title": "15.5.1 dnr result object", "text": "node168.html node166.html node166.html node1.html node221.html\n---\n## 15.5.1 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@cnri.reston.va.us", "python_version": "1.4", "length": 879, "url": "https://docs.python.org/{python_version}/lib/node167.html"} {"title": "15.6 Built-in Module macfs", "text": "node169.html node158.html node167.html node1.html node221.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- 15.6.1 FSSpec objects (node169.html#SECTION001661000000000000000)\n15.6.2 alias objects (node170.html#SECTION001662000000000000000)\n15.6.3 FInfo objects (node171.html#SECTION001663000000000000000)\n---\nnode169.html node158.html node167.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 827, "url": "https://docs.python.org/{python_version}/lib/node168.html"} {"title": "15.6.1 FSSpec objects", "text": "node170.html node168.html node168.html node1.html node221.html\n---\n## 15.6.1 FSSpec objects\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 119, "url": "https://docs.python.org/{python_version}/lib/node169.html"} {"title": "Functions", "text": "node18.html node14.html node16.html node1.html node221.html\n---\n### Functions\nFunction objects are created by function definitions. The only\noperation on a function object is to call it:\n`func ( argument-list )`.\nThere are really two flavors of function objects: built-in functions\nand user-defined functions. Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\nThe implementation adds two special read-only attributes:\n`f .func_code` is a function's code object (see below) and\n`f .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@cnri.reston.va.us", "python_version": "1.4", "length": 753, "url": "https://docs.python.org/{python_version}/lib/node17.html"} {"title": "15.6.2 alias objects", "text": "node171.html node168.html node169.html node1.html node221.html\n---\n## 15.6.2 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@cnri.reston.va.us", "python_version": "1.4", "length": 398, "url": "https://docs.python.org/{python_version}/lib/node170.html"} {"title": "15.6.3 FInfo objects", "text": "node172.html node168.html node170.html node1.html node221.html\n---\n## 15.6.3 FInfo objects\nSee Inside Mac for a complete description of what the various fields\nmean.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 193, "url": "https://docs.python.org/{python_version}/lib/node171.html"} {"title": "15.7 Built-in Module MacOS", "text": "node173.html node158.html node171.html node1.html node221.html\n---\n# 15.7 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---\nnode173.html node158.html node171.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 427, "url": "https://docs.python.org/{python_version}/lib/node172.html"} {"title": "15.8 Standard module macostools", "text": "node174.html node158.html node172.html node1.html node221.html\n---\n# 15.8 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@cnri.reston.va.us", "python_version": "1.4", "length": 467, "url": "https://docs.python.org/{python_version}/lib/node173.html"} {"title": "15.9 Standard module findertools", "text": "node175.html node158.html node173.html node1.html node221.html\n---\n# 15.9 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@cnri.reston.va.us", "python_version": "1.4", "length": 475, "url": "https://docs.python.org/{python_version}/lib/node174.html"} {"title": "15.10 Built-in Module mactcp", "text": "node176.html node158.html node174.html node1.html node221.html\n---\n# 15.10 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\n`socket` 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- 15.10.1 TCP Stream Objects (node176.html#SECTION0016101000000000000000)\n15.10.2 TCP Status Objects (node177.html#SECTION0016102000000000000000)\n15.10.3 UDP Stream Objects (node178.html#SECTION0016103000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 892, "url": "https://docs.python.org/{python_version}/lib/node175.html"} {"title": "15.10.1 TCP Stream Objects", "text": "node177.html node175.html node175.html node1.html node221.html\n---\n## 15.10.1 TCP Stream Objects\n---\nnode177.html node175.html node175.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 187, "url": "https://docs.python.org/{python_version}/lib/node176.html"} {"title": "15.10.2 TCP Status Objects", "text": "node178.html node175.html node176.html node1.html node221.html\n---\n## 15.10.2 TCP Status Objects\nThis object has no methods, only some members holding information on\nthe connection. A complete description of all fields in this objects\ncan be found in the Apple documentation. The most interesting ones are:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 334, "url": "https://docs.python.org/{python_version}/lib/node177.html"} {"title": "15.10.3 UDP Stream Objects", "text": "node179.html node175.html node177.html node1.html node221.html\n---\n## 15.10.3 UDP Stream Objects\nNote that, unlike the name suggests, there is nothing stream-like\nabout UDP.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 201, "url": "https://docs.python.org/{python_version}/lib/node178.html"} {"title": "15.11 Built-in Module macspeech", "text": "node180.html node158.html node178.html node1.html node221.html\n---\n# 15.11 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- 15.11.1 voice objects (node180.html#SECTION0016111000000000000000)\n15.11.2 speech channel objects (node181.html#SECTION0016112000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 662, "url": "https://docs.python.org/{python_version}/lib/node179.html"} {"title": "Methods", "text": "node19.html node14.html node17.html node1.html node221.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 , ..., arg-n )` is completely equivalent to calling\n`m .im_func( m .im_self, arg-1 , arg-2 ,\n..., arg-n )`.\n(See the Python Reference Manual for more info.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 709, "url": "https://docs.python.org/{python_version}/lib/node18.html"} {"title": "15.11.1 voice objects", "text": "node181.html node179.html node179.html node1.html node221.html\n---\n## 15.11.1 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@cnri.reston.va.us", "python_version": "1.4", "length": 239, "url": "https://docs.python.org/{python_version}/lib/node180.html"} {"title": "15.11.2 speech channel objects", "text": "node182.html node179.html node180.html node1.html node221.html\n---\n## 15.11.2 speech channel objects\nA speech channel object allows you to speak strings with slightly more\ncontrol than `SpeakString()`, and allows you to use multiple\nspeakers at the same time. Please note that channel pitch and rate are\ninterrelated in some way, so that to make your Macintosh sing you will\nhave to adjust both.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 423, "url": "https://docs.python.org/{python_version}/lib/node181.html"} {"title": "15.12 Standard module EasyDialogs", "text": "node183.html node158.html node181.html node1.html node221.html\n---\n# 15.12 Standard module `EasyDialogs`\nThe `EasyDialogs` module contains some simple dialogs for\nthe Macintosh, modelled after the `stdwin` dialogs with similar\nnames.\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---\nnode183.html node158.html node181.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 796, "url": "https://docs.python.org/{python_version}/lib/node182.html"} {"title": "15.13 Standard module FrameWork", "text": "node184.html node158.html node182.html node1.html node221.html\n---\n# 15.13 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- 15.13.1 Application objects (node184.html#SECTION0016131000000000000000)\n15.13.2 Window Objects (node185.html#SECTION0016132000000000000000)\n15.13.3 ControlsWindow Object (node186.html#SECTION0016133000000000000000)\n15.13.4 ScrolledWindow Object (node187.html#SECTION0016134000000000000000)\n15.13.5 DialogWindow Objects (node188.html#SECTION0016135000000000000000)\n---\nnode184.html node158.html node182.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1319, "url": "https://docs.python.org/{python_version}/lib/node183.html"} {"title": "15.13.1 Application objects", "text": "node185.html node183.html node183.html node1.html node221.html\n---\n## 15.13.1 Application objects\nApplication objects have the following methods, among others:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 187, "url": "https://docs.python.org/{python_version}/lib/node184.html"} {"title": "15.13.2 Window Objects", "text": "node186.html node183.html node184.html node1.html node221.html\n---\n## 15.13.2 Window Objects\nWindow objects have the following methods, among others:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 177, "url": "https://docs.python.org/{python_version}/lib/node185.html"} {"title": "15.13.3 ControlsWindow Object", "text": "node187.html node183.html node185.html node1.html node221.html\n---\n## 15.13.3 ControlsWindow Object\nControlsWindow objects have the following methods besides those of\n`Window` objects:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 212, "url": "https://docs.python.org/{python_version}/lib/node186.html"} {"title": "15.13.4 ScrolledWindow Object", "text": "node188.html node183.html node186.html node1.html node221.html\n---\n## 15.13.4 ScrolledWindow Object\nScrolledWindow objects are ControlsWindow objects with the following\nextra methods:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 211, "url": "https://docs.python.org/{python_version}/lib/node187.html"} {"title": "15.13.5 DialogWindow Objects", "text": "node189.html node183.html node187.html node1.html node221.html\n---\n## 15.13.5 DialogWindow Objects\nDialogWindow objects have the following methods besides those of\n`Window` objects:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 209, "url": "https://docs.python.org/{python_version}/lib/node188.html"} {"title": "15.14 Standard module MiniAEFrame", "text": "node190.html node158.html node188.html node1.html node221.html\n---\n# 15.14 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- 15.14.1 AEServer Objects (node190.html#SECTION0016141000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 622, "url": "https://docs.python.org/{python_version}/lib/node189.html"} {"title": "Code Objects", "text": "node20.html node14.html node18.html node1.html node221.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\n`eval()` function.\n(See the Python Reference Manual for more info.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 682, "url": "https://docs.python.org/{python_version}/lib/node19.html"} {"title": "15.14.1 AEServer Objects", "text": "node191.html node189.html node189.html node1.html node221.html\n---\n## 15.14.1 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@cnri.reston.va.us", "python_version": "1.4", "length": 388, "url": "https://docs.python.org/{python_version}/lib/node190.html"} {"title": "16 Standard Windowing Interface", "text": "node192.html lib.html node190.html node1.html node221.html\n---\n# 16 Standard Windowing Interface\nThe modules in this chapter are available only on those systems where\nthe STDWIN library is available. STDWIN runs on Unix under X11 and\non the Macintosh. See CWI report CS-R8817.\nWarning: Using STDWIN is not recommended for new\napplications. It has never been ported to Microsoft Windows or\nWindows NT, and for X11 or the Macintosh it lacks important\nfunctionality -- in particular, it has no tools for the construction\nof dialogs. For most platforms, alternative, native solutions exist\n(though none are currently documented in this manual): Tkinter for\nUnix under X11, native Xt with Motif or Athena widgets for Unix\nunder X11, Win32 for Windows and Windows NT, and a collection of\nnative toolkit interfaces for the Macintosh.\n---\n- 16.1 Built-in Module `stdwin` (node192.html#SECTION001710000000000000000)\n- 16.1.1 Functions Defined in Module `stdwin` (node193.html#SECTION001711000000000000000)\n16.1.2 Window Objects (node194.html#SECTION001712000000000000000)\n16.1.3 Drawing Objects (node195.html#SECTION001713000000000000000)\n16.1.4 Menu Objects (node196.html#SECTION001714000000000000000)\n16.1.5 Bitmap Objects (node197.html#SECTION001715000000000000000)\n16.1.6 Text-edit Objects (node198.html#SECTION001716000000000000000)\n16.1.7 Example (node199.html#SECTION001717000000000000000)\n16.2 Standard Module `stdwinevents` (node200.html#SECTION001720000000000000000)\n16.3 Standard Module `rect` (node201.html#SECTION001730000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1567, "url": "https://docs.python.org/{python_version}/lib/node191.html"} {"title": "16.1 Built-in Module stdwin", "text": "node193.html node191.html node191.html node1.html node221.html\n---\n# 16.1 Built-in Module `stdwin`\nThis module defines several new object types and functions that\nprovide access to the functionality of STDWIN.\nOn Unix running X11, it can only be used if the `DISPLAY`\nenvironment variable is set or an explicit `-display\ndisplayname' argument is passed to the Python interpreter.\nFunctions have names that usually resemble their C STDWIN counterparts\nwith the initial `w' dropped.\nPoints are represented by pairs of integers; rectangles\nby pairs of points.\nFor a complete description of STDWIN please refer to the documentation\nof STDWIN for C programmers (aforementioned CWI report).\n---\n- 16.1.1 Functions Defined in Module `stdwin` (node193.html#SECTION001711000000000000000)\n16.1.2 Window Objects (node194.html#SECTION001712000000000000000)\n16.1.3 Drawing Objects (node195.html#SECTION001713000000000000000)\n16.1.4 Menu Objects (node196.html#SECTION001714000000000000000)\n16.1.5 Bitmap Objects (node197.html#SECTION001715000000000000000)\n16.1.6 Text-edit Objects (node198.html#SECTION001716000000000000000)\n16.1.7 Example (node199.html#SECTION001717000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1197, "url": "https://docs.python.org/{python_version}/lib/node192.html"} {"title": "16.1.1 Functions Defined in Module stdwin", "text": "node194.html node192.html node192.html node1.html node221.html\n---\n## 16.1.1 Functions Defined in Module `stdwin`\nThe following functions are defined in the `stdwin` module:\n---\nnode194.html node192.html node192.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 264, "url": "https://docs.python.org/{python_version}/lib/node193.html"} {"title": "16.1.2 Window Objects", "text": "node195.html node192.html node193.html node1.html node221.html\n---\n## 16.1.2 Window Objects\nWindow objects are created by `stdwin.open()`. They are closed\nby their `close()` method or when they are garbage-collected.\nWindow objects have the following methods:\n---\nnode195.html node192.html node193.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 350, "url": "https://docs.python.org/{python_version}/lib/node194.html"} {"title": "16.1.3 Drawing Objects", "text": "node196.html node192.html node194.html node1.html node221.html\n---\n## 16.1.3 Drawing Objects\nDrawing objects are created exclusively by the window method\n`begindrawing()`.\nOnly one drawing object can exist at any given time; the drawing object\nmust be deleted to finish drawing.\nNo drawing object may exist when\n`stdwin.getevent()`\nis called.\nDrawing objects have the following methods:\n---\nnode196.html node192.html node194.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 477, "url": "https://docs.python.org/{python_version}/lib/node195.html"} {"title": "16.1.4 Menu Objects", "text": "node197.html node192.html node195.html node1.html node221.html\n---\n## 16.1.4 Menu Objects\nA menu object represents a menu.\nThe menu is destroyed when the menu object is deleted.\nThe following methods are defined:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 240, "url": "https://docs.python.org/{python_version}/lib/node196.html"} {"title": "16.1.5 Bitmap Objects", "text": "node198.html node192.html node196.html node1.html node221.html\n---\n## 16.1.5 Bitmap Objects\nA bitmap represents a rectangular array of bits.\nThe top left bit has coordinate (0, 0).\nA bitmap can be drawn with the `bitmap` method of a drawing object.\nBitmaps are currently not available on the Macintosh.\nThe following methods are defined:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 365, "url": "https://docs.python.org/{python_version}/lib/node197.html"} {"title": "16.1.6 Text-edit Objects", "text": "node199.html node192.html node197.html node1.html node221.html\n---\n## 16.1.6 Text-edit Objects\nA text-edit object represents a text-edit block.\nFor semantics, see the STDWIN documentation for C programmers.\nThe following methods exist:\n---\nnode199.html node192.html node197.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 326, "url": "https://docs.python.org/{python_version}/lib/node198.html"} {"title": "16.1.7 Example", "text": "node200.html node192.html node198.html node1.html node221.html\n---\n## 16.1.7 Example\nHere is a minimal example of using STDWIN in Python.\nIt creates a window and draws the string ``Hello world'' in the top\nleft corner of the window.\nThe window will be correctly redrawn when covered and re-exposed.\nThe program quits when the close icon or menu item is requested.\n```text\nimport stdwin\nfrom stdwinevents import *\n\ndef main():\nmywin = stdwin.open('Hello')\n#\nwhile 1:\n(type, win, detail) = stdwin.getevent()\nif type == WE_DRAW:\ndraw = win.begindrawing()\ndraw.text((0, 0), 'Hello, world')\ndel draw\nelif type == WE_CLOSE:\nbreak\n\nmain()\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 663, "url": "https://docs.python.org/{python_version}/lib/node199.html"} {"title": "1 Introduction", "text": "node3.html lib.html node1.html node1.html node221.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\n`import` 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\n`rand`) and read a section or two.\nLet the show begin!\n---\nnode3.html lib.html node1.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2654, "url": "https://docs.python.org/{python_version}/lib/node2.html"} {"title": "Type Objects", "text": "node21.html node14.html node19.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 383, "url": "https://docs.python.org/{python_version}/lib/node20.html"} {"title": "16.2 Standard Module stdwinevents", "text": "node201.html node191.html node199.html node1.html node221.html\n---\n# 16.2 Standard Module `stdwinevents`\nThis module defines constants used by STDWIN for event types\n(`WE_ACTIVATE` etc.), command codes (`WC_LEFT` etc.)\nand selection types (`WS_PRIMARY` etc.).\nRead the file for details.\nSuggested usage is\n```text\n>>> from stdwinevents import *\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 380, "url": "https://docs.python.org/{python_version}/lib/node200.html"} {"title": "16.3 Standard Module rect", "text": "node202.html node191.html node200.html node1.html node221.html\n---\n# 16.3 Standard Module `rect`\nThis module contains useful operations on rectangles.\nA rectangle is defined as in module\n`stdwin`:\na pair of points, where a point is a pair of integers.\nFor example, the rectangle\n```text\n(10, 20), (90, 80)\n```\nis a rectangle whose left, top, right and bottom edges are 10, 20, 90\nand 80, respectively.\nNote that the positive vertical axis points down (as in\n`stdwin`).\nThe module defines the following objects:\n---\nnode202.html node191.html node200.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 601, "url": "https://docs.python.org/{python_version}/lib/node201.html"} {"title": "17 SGI IRIX Specific Services", "text": "node203.html lib.html node201.html node1.html node221.html\n---\n# 17 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- 17.1 Built-in Module `al` (node203.html#SECTION001810000000000000000)\n- 17.1.1 Configuration Objects (node204.html#SECTION001811000000000000000)\n17.1.2 Port Objects (node205.html#SECTION001812000000000000000)\n17.2 Standard Module `AL` (node206.html#SECTION001820000000000000000)\n17.3 Built-in Module `cd` (node207.html#SECTION001830000000000000000)\n17.4 Built-in Module `fl` (node208.html#SECTION001840000000000000000)\n- 17.4.1 Functions Defined in Module `fl` (node209.html#SECTION001841000000000000000)\n17.4.2 Form Objects (node210.html#SECTION001842000000000000000)\n17.4.3 FORMS Objects (node211.html#SECTION001843000000000000000)\n17.5 Standard Module `FL` (node212.html#SECTION001850000000000000000)\n17.6 Standard Module `flp` (node213.html#SECTION001860000000000000000)\n17.7 Built-in Module `fm` (node214.html#SECTION001870000000000000000)\n17.8 Built-in Module `gl` (node215.html#SECTION001880000000000000000)\n17.9 Standard Modules `GL` and `DEVICE` (node216.html#SECTION001890000000000000000)\n17.10 Built-in Module `imgfile` (node217.html#SECTION0018100000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1340, "url": "https://docs.python.org/{python_version}/lib/node202.html"} {"title": "17.1 Built-in Module al", "text": "node204.html node202.html node202.html node1.html node221.html\n---\n# 17.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- 17.1.1 Configuration Objects (node204.html#SECTION001811000000000000000)\n17.1.2 Port Objects (node205.html#SECTION001812000000000000000)\n---\nnode204.html node202.html node202.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1395, "url": "https://docs.python.org/{python_version}/lib/node203.html"} {"title": "17.1.1 Configuration Objects", "text": "node205.html node203.html node203.html node1.html node221.html\n---\n## 17.1.1 Configuration Objects\nConfiguration objects (returned by `al.newconfig()` have the\nfollowing methods:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 206, "url": "https://docs.python.org/{python_version}/lib/node204.html"} {"title": "17.1.2 Port Objects", "text": "node206.html node203.html node204.html node1.html node221.html\n---\n## 17.1.2 Port Objects\nPort objects (returned by `al.openport()` have the following\nmethods:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 187, "url": "https://docs.python.org/{python_version}/lib/node205.html"} {"title": "17.2 Standard Module AL", "text": "node207.html node202.html node205.html node1.html node221.html\n---\n# 17.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@cnri.reston.va.us", "python_version": "1.4", "length": 450, "url": "https://docs.python.org/{python_version}/lib/node206.html"} {"title": "17.3 Built-in Module cd", "text": "node208.html node202.html node206.html node1.html node221.html\n---\n# 17.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\n`cd.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---\nnode208.html node202.html node206.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1749, "url": "https://docs.python.org/{python_version}/lib/node207.html"} {"title": "17.4 Built-in Module fl", "text": "node209.html node202.html node207.html node1.html node221.html\n---\n# 17.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\n`fl_addto_form` and `fl_end_form`, and the equivalent of\n`fl_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\n`foreground()` and to the FORMS routine `fl_init()`.\n---\n- 17.4.1 Functions Defined in Module `fl` (node209.html#SECTION001841000000000000000)\n17.4.2 Form Objects (node210.html#SECTION001842000000000000000)\n17.4.3 FORMS Objects (node211.html#SECTION001843000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1907, "url": "https://docs.python.org/{python_version}/lib/node208.html"} {"title": "17.4.1 Functions Defined in Module fl", "text": "node210.html node208.html node208.html node1.html node221.html\n---\n## 17.4.1 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---\nnode210.html node208.html node208.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 363, "url": "https://docs.python.org/{python_version}/lib/node209.html"} {"title": "The Null Object", "text": "node22.html node14.html node20.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 312, "url": "https://docs.python.org/{python_version}/lib/node21.html"} {"title": "17.4.2 Form Objects", "text": "node211.html node208.html node209.html node1.html node221.html\n---\n## 17.4.2 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:\n---\nnode211.html node208.html node209.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 754, "url": "https://docs.python.org/{python_version}/lib/node210.html"} {"title": "17.4.3 FORMS Objects", "text": "node212.html node208.html node210.html node1.html node221.html\n---\n## 17.4.3 FORMS Objects\nBesides methods specific to particular kinds of FORMS objects, all\nFORMS objects also have the following methods:\nFORMS objects have these data attributes; see the FORMS documentation:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 303, "url": "https://docs.python.org/{python_version}/lib/node211.html"} {"title": "17.5 Standard Module FL", "text": "node213.html node202.html node211.html node1.html node221.html\n---\n# 17.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@cnri.reston.va.us", "python_version": "1.4", "length": 450, "url": "https://docs.python.org/{python_version}/lib/node212.html"} {"title": "17.6 Standard Module flp", "text": "node214.html node202.html node212.html node1.html node221.html\n---\n# 17.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@cnri.reston.va.us", "python_version": "1.4", "length": 438, "url": "https://docs.python.org/{python_version}/lib/node213.html"} {"title": "17.7 Built-in Module fm", "text": "node215.html node202.html node213.html node1.html node221.html\n---\n# 17.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---\nnode215.html node202.html node213.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 733, "url": "https://docs.python.org/{python_version}/lib/node214.html"} {"title": "17.8 Built-in Module gl", "text": "node216.html node202.html node214.html node1.html node221.html\n---\n# 17.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,\n`winopen('Hi There!')`\nand\n`rotate(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---\nnode216.html node202.html node214.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2356, "url": "https://docs.python.org/{python_version}/lib/node215.html"} {"title": "17.9 Standard Modules GL and DEVICE", "text": "node217.html node202.html node215.html node1.html node221.html\n---\n# 17.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@cnri.reston.va.us", "python_version": "1.4", "length": 340, "url": "https://docs.python.org/{python_version}/lib/node216.html"} {"title": "17.10 Built-in Module imgfile", "text": "node218.html node202.html node216.html node1.html node221.html\n---\n# 17.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---\nnode218.html node202.html node216.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 520, "url": "https://docs.python.org/{python_version}/lib/node217.html"} {"title": "18 SunOS Specific Services", "text": "node219.html lib.html node217.html node1.html node221.html\n---\n# 18 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- 18.1 Built-in Module `sunaudiodev` (node219.html#SECTION001910000000000000000)\n- 18.1.1 Audio Device Objects (node220.html#SECTION001911000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 460, "url": "https://docs.python.org/{python_version}/lib/node218.html"} {"title": "18.1 Built-in Module sunaudiodev", "text": "node220.html node218.html node218.html node1.html node221.html\n---\n# 18.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- 18.1.1 Audio Device Objects (node220.html#SECTION001911000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 504, "url": "https://docs.python.org/{python_version}/lib/node219.html"} {"title": "File Objects", "text": "node23.html node14.html node21.html node1.html node221.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\n`posix.fdopen()` and the `makefile()` method of socket\nobjects.\nWhen a file operation fails for an I/O-related reason, the exception\n`IOError` 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:\n---\nnode23.html node14.html node21.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 747, "url": "https://docs.python.org/{python_version}/lib/node22.html"} {"title": "18.1.1 Audio Device Objects", "text": "node221.html node219.html node219.html node1.html node221.html\n---\n## 18.1.1 Audio Device Objects\nThe audio device objects are returned by `open` define the\nfollowing methods (except `control` objects which only provide\ngetinfo, setinfo and drain):\nThere is a companion module, `SUNAUDIODEV`, which defines useful\nsymbolic constants like `MIN_GAIN`, `MAX_GAIN`,\n`SPEAKER`, etc. The names of\nthe constants are the same names as used in the C include file\n```', with the leading string `AUDIO_' stripped.\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---\nnode221.html node219.html node219.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 762, "url": "https://docs.python.org/{python_version}/lib/node220.html"} {"title": "Index", "text": "node222.html lib.html node220.html node1.html\n---\n## Index\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 86, "url": "https://docs.python.org/{python_version}/lib/node221.html"} {"title": "About this document ...", "text": "lib.html node221.html node1.html node221.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@cnri.reston.va.us lib.tex.\nThe translation was initiated by Fred L. Drake on Fri Dec 6 09:14:53 EST 1996\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 591, "url": "https://docs.python.org/{python_version}/lib/node222.html"} {"title": "Internal Objects", "text": "node24.html node14.html node22.html node1.html node221.html\n---\n### Internal Objects\n(See the Python Reference Manual for these.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 157, "url": "https://docs.python.org/{python_version}/lib/node23.html"} {"title": "2.1.8 Special Attributes", "text": "node25.html node4.html node23.html node1.html node221.html\n---\n## 2.1.8 Special Attributes\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant:\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@cnri.reston.va.us", "python_version": "1.4", "length": 650, "url": "https://docs.python.org/{python_version}/lib/node24.html"} {"title": "2.2 Built-in Exceptions", "text": "node26.html node3.html node24.html node1.html node221.html\n---\n# 2.2 Built-in Exceptions\nExceptions are string objects. Two distinct string objects with the\nsame value are different exceptions. This is done to force programmers\nto use exception names rather than their string value when specifying\nexception handlers. The string value of all built-in exceptions is\ntheir name, but this is not a requirement for user-defined exceptions\nor exceptions defined by library modules.\nThe following exceptions can be generated by the interpreter or\nbuilt-in functions. Except where mentioned, they have an `associated\nvalue' indicating the detailed cause of the error. This may be a\nstring or a tuple containing several items of information (e.g., an\nerror code and a string explaining the code).\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.\n---\nnode26.html node3.html node24.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1163, "url": "https://docs.python.org/{python_version}/lib/node25.html"} {"title": "2.3 Built-in Functions", "text": "node27.html node3.html node25.html node1.html node221.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 node3.html node25.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 308, "url": "https://docs.python.org/{python_version}/lib/node26.html"} {"title": "3 Python Services", "text": "node28.html lib.html node26.html node1.html node221.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#SECTION00410000000000000000)\n3.2 Standard Module `types` (node29.html#SECTION00420000000000000000)\n3.3 Standard Module `traceback` (node30.html#SECTION00430000000000000000)\n3.4 Standard Module `pickle` (node31.html#SECTION00440000000000000000)\n3.5 Standard Module `shelve` (node32.html#SECTION00450000000000000000)\n3.6 Standard Module `copy` (node33.html#SECTION00460000000000000000)\n3.7 Built-in Module `marshal` (node34.html#SECTION00470000000000000000)\n3.8 Built-in Module `imp` (node35.html#SECTION00480000000000000000)\n- 3.8.1 Examples (node36.html#SECTION00481000000000000000)\n3.9 Built-in Module `parser` (node37.html#SECTION00490000000000000000)\n- 3.9.1 Creating AST Objects (node38.html#SECTION00491000000000000000)\n3.9.2 Converting AST Objects (node39.html#SECTION00492000000000000000)\n3.9.3 Queries on AST Objects (node40.html#SECTION00493000000000000000)\n3.9.4 Exceptions and Error Handling (node41.html#SECTION00494000000000000000)\n3.9.5 AST Objects (node42.html#SECTION00495000000000000000)\n3.9.6 Examples (node43.html#SECTION00496000000000000000)\n- Emulation of `compile()` (node44.html#SECTION00496100000000000000)\nInformation Discovery (node45.html#SECTION00496200000000000000)\n3.10 Built-in Module `__builtin__` (node46.html#SECTION004100000000000000000)\n3.11 Built-in Module `__main__` (node47.html#SECTION004110000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1668, "url": "https://docs.python.org/{python_version}/lib/node27.html"} {"title": "3.1 Built-in Module sys", "text": "node29.html node27.html node27.html node1.html node221.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 node27.html node27.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 349, "url": "https://docs.python.org/{python_version}/lib/node28.html"} {"title": "3.2 Standard Module types", "text": "node30.html node27.html node28.html node1.html node221.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 node27.html node28.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 806, "url": "https://docs.python.org/{python_version}/lib/node29.html"} {"title": "2 Built-in Types, Exceptions and Functions", "text": "node4.html lib.html node2.html node1.html node221.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#25\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#SECTION00310000000000000000)\n- 2.1.1 Truth Value Testing (node5.html#SECTION00311000000000000000)\n2.1.2 Boolean Operations (node6.html#SECTION00312000000000000000)\n2.1.3 Comparisons (node7.html#SECTION00313000000000000000)\n2.1.4 Numeric Types (node8.html#SECTION00314000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION00314100000000000000)\n2.1.5 Sequence Types (node10.html#SECTION00315000000000000000)\n- More String Operations (node11.html#SECTION00315100000000000000)\nMutable Sequence Types (node12.html#SECTION00315200000000000000)\n2.1.6 Mapping Types (node13.html#SECTION00316000000000000000)\n2.1.7 Other Built-in Types (node14.html#SECTION00317000000000000000)\n- Modules (node15.html#SECTION00317100000000000000)\nClasses and Class Instances (node16.html#SECTION00317200000000000000)\nFunctions (node17.html#SECTION00317300000000000000)\nMethods (node18.html#SECTION00317400000000000000)\nCode Objects (node19.html#SECTION00317500000000000000)\nType Objects (node20.html#SECTION00317600000000000000)\nThe Null Object (node21.html#SECTION00317700000000000000)\nFile Objects (node22.html#SECTION00317800000000000000)\nInternal Objects (node23.html#SECTION00317900000000000000)\n2.1.8 Special Attributes (node24.html#SECTION00318000000000000000)\n2.2 Built-in Exceptions (node25.html#SECTION00320000000000000000)\n2.3 Built-in Functions (node26.html#SECTION00330000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2307, "url": "https://docs.python.org/{python_version}/lib/node3.html"} {"title": "3.3 Standard Module traceback", "text": "node31.html node27.html node29.html node1.html node221.html\n---\n# 3.3 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\n`sys.last_traceback`.\nThe module defines the following functions:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 610, "url": "https://docs.python.org/{python_version}/lib/node30.html"} {"title": "3.4 Standard Module pickle", "text": "node32.html node27.html node30.html node1.html node221.html\n---\n# 3.4 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\n`shelve` provides a simple interface to pickle and unpickle\nobjects on ``dbm''-style database files.\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 CORBA (which probably can't represent pointer\nsharing or recursive objects); however it means that non-Python\nprograms may not be able to reconstruct pickled Python objects.\nThe `pickle` data format uses a printable ASCII representation.\nThis is slightly more voluminous than a binary representation.\nHowever, small integers actually take less space when\nrepresented as minimal-size decimal strings than when represented as\n32-bit binary numbers, and strings are only much longer if they\ncontain many control characters or 8-bit characters. The big\nadvantage of using printable ASCII (and of some other characteristics\nof `pickle`'s representation) is that for debugging or recovery\npurposes it is possible for a human to read the pickled file with a\nstandard text editor. (I could have gone a step further and used a\nnotation like S-expressions, but the parser\n(currently written in Python) would have been\nconsiderably more complicated and slower, and the files would probably\nhave become much larger.)\nThe `pickle` module doesn't handle code objects, which the\n`marshal` 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\n`persistent_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.\nNext, it must normally be possible to create class instances by\ncalling the class without arguments. Usually, this is best\naccomplished by providing default values for all arguments to its\n`__init__` method (if it has one). If this is undesirable, the\nclass can define a method `__getinitargs__()`, which should\nreturn a tuple containing the arguments to be passed to the\nclass constructor (`__init__()`).\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 following types can be pickled:\n- `None`integers, 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\n`PicklingError` 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\n`Unpickler` 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---\nnode32.html node27.html node30.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 7638, "url": "https://docs.python.org/{python_version}/lib/node31.html"} {"title": "3.5 Standard Module shelve", "text": "node33.html node27.html node31.html node1.html node221.html\n---\n# 3.5 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\n`pickle` 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 gdbm)\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.Dependent 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@cnri.reston.va.us", "python_version": "1.4", "length": 1983, "url": "https://docs.python.org/{python_version}/lib/node32.html"} {"title": "3.6 Standard Module copy", "text": "node34.html node27.html node32.html node1.html node221.html\n---\n# 3.6 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@cnri.reston.va.us", "python_version": "1.4", "length": 1817, "url": "https://docs.python.org/{python_version}/lib/node33.html"} {"title": "3.7 Built-in Module marshal", "text": "node35.html node27.html node33.html node1.html node221.html\n---\n# 3.7 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#1971\nThis is not a general ``persistency'' module. For general persistency\nand transfer of Python objects through RPC calls, see the modules\n`pickle` 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:\n`None`, 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#2020\nThere are functions that read/write files as well as functions\noperating on strings.\nThe module defines these functions:\n---\nnode35.html node27.html node33.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2103, "url": "https://docs.python.org/{python_version}/lib/node34.html"} {"title": "3.8 Built-in Module imp", "text": "node36.html node27.html node34.html node1.html node221.html\n---\n# 3.8 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 the module,\nare used to indicate the search result of `imp.find_module`.\n---\n- 3.8.1 Examples (node36.html#SECTION00481000000000000000)\n---\nnode36.html node27.html node34.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 515, "url": "https://docs.python.org/{python_version}/lib/node35.html"} {"title": "3.8.1 Examples", "text": "node37.html node35.html node35.html node1.html node221.html\n---\n## 3.8.1 Examples\nThe following function emulates the default import statement:\n```text\nimport imp\nimport sys\n\ndef __import__(name, globals=None, locals=None, fromlist=None):\n# Fast path: see if the module has already been imported.\nif sys.modules.has_key(name):\nreturn sys.modules[name]\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\n# See if it's a built-in module.\nm = imp.init_builtin(name)\nif m:\nreturn m\n\n# See if it's a frozen module.\nm = imp.init_frozen(name)\nif m:\nreturn m\n\n# Search the default path (i.e. sys.path).\nfp, pathname, (suffix, mode, type) = imp.find_module(name)\n\n# See what we got.\ntry:\nif type == imp.C_EXTENSION:\nreturn imp.load_dynamic(name, pathname)\nif type == imp.PY_SOURCE:\nreturn imp.load_source(name, pathname, fp)\nif type == imp.PY_COMPILED:\nreturn imp.load_compiled(name, pathname, fp)\n\n# Shouldn't get here at all.\nraise ImportError, '%s: unknown module type (%d)' % (name, type)\nfinally:\n# Since we may exit via an exception, close fp explicitly.\nfp.close()\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1163, "url": "https://docs.python.org/{python_version}/lib/node36.html"} {"title": "3.9 Built-in Module parser", "text": "node38.html node27.html node36.html node1.html node221.html\n---\n# 3.9 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 Language Reference. The parser itself\nis 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\n`expr()` 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\n`ast2tuple()` 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\n``Lib/symbol.py`'. 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\n`if` 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\n``Lib/token.py`'.\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; the `AST` library module provides a variety of such\nclasses.\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- 3.9.1 Creating AST Objects (node38.html#SECTION00491000000000000000)\n3.9.2 Converting AST Objects (node39.html#SECTION00492000000000000000)\n3.9.3 Queries on AST Objects (node40.html#SECTION00493000000000000000)\n3.9.4 Exceptions and Error Handling (node41.html#SECTION00494000000000000000)\n3.9.5 AST Objects (node42.html#SECTION00495000000000000000)\n3.9.6 Examples (node43.html#SECTION00496000000000000000)\n- Emulation of `compile()` (node44.html#SECTION00496100000000000000)\nInformation Discovery (node45.html#SECTION00496200000000000000)\n---\nnode38.html node27.html node36.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 4996, "url": "https://docs.python.org/{python_version}/lib/node37.html"} {"title": "3.9.1 Creating AST Objects", "text": "node39.html node37.html node37.html node1.html node221.html\n---\n## 3.9.1 Creating AST Objects\nAST objects may be created from source code or from a parse tree.\nWhen creating an AST object from source, different functions are used\nto create the `'eval'` and `'exec'` forms.\n---\nnode39.html node37.html node37.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 360, "url": "https://docs.python.org/{python_version}/lib/node38.html"} {"title": "3.9.2 Converting AST Objects", "text": "node40.html node37.html node38.html node1.html node221.html\n---\n## 3.9.2 Converting AST Objects\nAST objects, regardless of the input used to create them, may be\nconverted to parse trees represented as list- or tuple- trees, or may\nbe compiled into executable code objects. Parse trees may be\nextracted with or without line numbering information.\n---\nnode40.html node37.html node38.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 433, "url": "https://docs.python.org/{python_version}/lib/node39.html"} {"title": "2.1 Built-in Types", "text": "node5.html node3.html node3.html node1.html node221.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- 2.1.1 Truth Value Testing (node5.html#SECTION00311000000000000000)\n2.1.2 Boolean Operations (node6.html#SECTION00312000000000000000)\n2.1.3 Comparisons (node7.html#SECTION00313000000000000000)\n2.1.4 Numeric Types (node8.html#SECTION00314000000000000000)\n- Bit-string Operations on Integer Types (node9.html#SECTION00314100000000000000)\n2.1.5 Sequence Types (node10.html#SECTION00315000000000000000)\n- More String Operations (node11.html#SECTION00315100000000000000)\nMutable Sequence Types (node12.html#SECTION00315200000000000000)\n2.1.6 Mapping Types (node13.html#SECTION00316000000000000000)\n2.1.7 Other Built-in Types (node14.html#SECTION00317000000000000000)\n- Modules (node15.html#SECTION00317100000000000000)\nClasses and Class Instances (node16.html#SECTION00317200000000000000)\nFunctions (node17.html#SECTION00317300000000000000)\nMethods (node18.html#SECTION00317400000000000000)\nCode Objects (node19.html#SECTION00317500000000000000)\nType Objects (node20.html#SECTION00317600000000000000)\nThe Null Object (node21.html#SECTION00317700000000000000)\nFile Objects (node22.html#SECTION00317800000000000000)\nInternal Objects (node23.html#SECTION00317900000000000000)\n2.1.8 Special Attributes (node24.html#SECTION00318000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1858, "url": "https://docs.python.org/{python_version}/lib/node4.html"} {"title": "3.9.3 Queries on AST Objects", "text": "node41.html node37.html node39.html node1.html node221.html\n---\n## 3.9.3 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 via\n`sequence2ast()`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 400, "url": "https://docs.python.org/{python_version}/lib/node40.html"} {"title": "3.9.4 Exceptions and Error Handling", "text": "node42.html node37.html node40.html node1.html node221.html\n---\n## 3.9.4 Exceptions and Error Handling\nThe parser module defines a single exception, but may also pass other\nbuilt-in exceptions from other portions of the Python runtime\nenvironment. See each function for information about the exceptions\nit can raise.\nNote that the functions `compileast()`, `expr()`, and\n`suite()` may throw exceptions which are normally thrown by the\nparsing and compilation process. These include the built in\nexceptions `MemoryError`, `OverflowError`,\n`SyntaxError`, 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@cnri.reston.va.us", "python_version": "1.4", "length": 754, "url": "https://docs.python.org/{python_version}/lib/node41.html"} {"title": "3.9.5 AST Objects", "text": "node43.html node37.html node41.html node1.html node221.html\n---\n## 3.9.5 AST Objects\nAST objects returned by `expr()`, `suite()`, and\n`sequence2ast()` 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@cnri.reston.va.us", "python_version": "1.4", "length": 468, "url": "https://docs.python.org/{python_version}/lib/node42.html"} {"title": "3.9.6 Examples", "text": "node44.html node37.html node42.html node1.html node221.html\n---\n## 3.9.6 Examples\nThe parser modules allows operations to be performed on the parse tree\nof Python source code before the bytecode is generated, and provides\nfor inspection of the parse tree for information gathering purposes.\nTwo examples are presented. The simple example demonstrates emulation\nof the `compile()` built-in function and the complex example\nshows the use of a parse tree for information discovery.\n---\n- Emulation of `compile()` (node44.html#SECTION00496100000000000000)\nInformation Discovery (node45.html#SECTION00496200000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 643, "url": "https://docs.python.org/{python_version}/lib/node43.html"} {"title": "Emulation of compile()", "text": "node45.html node43.html node43.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 1074, "url": "https://docs.python.org/{python_version}/lib/node44.html"} {"title": "Information Discovery", "text": "node46.html node43.html node44.html node1.html node221.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\n`import`. 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\n`stmt`, `NEWLINE`, and `ENDMARKER`, respectively.\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()`,\n`get_class_names()`, and `get_class_info()`. The\n`ClassInfo` objects support `get_method_names()` and\n`get_method_info()` while the other classes provide\n`get_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 paralels 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. Since most\nfunctions and methods which use the short form do not provide a\ndocstring, this may be considered sufficient. The extraction of the\ndocstring proceeds using the `match()` function as described\nabove, and the value of the docstring is stored as an attribute of the\n`SuiteInfoBase` object.\nAfter docstring extraction, a simple definition discovery\nalgorithm operates on the `stmt` nodes of the `suite` node. The\nspecial case of the short form is not tested; since there are no\n`stmt` nodes in the short form, the algorithm will silently skip\nthe single `simple_stmt` node and correctly not discover any\nnested 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.\n---\nnode46.html node43.html node44.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 13646, "url": "https://docs.python.org/{python_version}/lib/node45.html"} {"title": "3.10 Built-in Module __builtin__", "text": "node47.html node27.html node45.html node1.html node221.html\n---\n# 3.10 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 the section on Built-in Functions in the\nprevious chapter.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 342, "url": "https://docs.python.org/{python_version}/lib/node46.html"} {"title": "3.11 Built-in Module __main__", "text": "node48.html node27.html node46.html node1.html node221.html\n---\n# 3.11 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@cnri.reston.va.us", "python_version": "1.4", "length": 296, "url": "https://docs.python.org/{python_version}/lib/node47.html"} {"title": "4 String Services", "text": "node49.html lib.html node47.html node1.html node221.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` (node49.html#SECTION00510000000000000000)\n4.2 Built-in Module `regex` (node50.html#SECTION00520000000000000000)\n- 4.2.1 Regular Expressions (node51.html#SECTION00521000000000000000)\n4.2.2 Module Contents (node52.html#SECTION00522000000000000000)\n4.3 Standard Module `regsub` (node53.html#SECTION00530000000000000000)\n4.4 Built-in Module `struct` (node54.html#SECTION00540000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 645, "url": "https://docs.python.org/{python_version}/lib/node48.html"} {"title": "4.1 Standard Module string", "text": "node50.html node48.html node48.html node1.html node221.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 modules\n`regex` and `regsub` for string functions based on regular\nexpressions.\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\n`string` discovers that `strop` exists, it transparently\nreplaces parts of itself with the implementation from `strop`.\nAfter initialization, there is no overhead in using\n`string` instead of `strop`.\n---\nnode50.html node48.html node48.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 851, "url": "https://docs.python.org/{python_version}/lib/node49.html"} {"title": "2.1.1 Truth Value Testing", "text": "node6.html node4.html node4.html node1.html node221.html\n---\n## 2.1.1 Truth Value Testing\nAny object can be tested for truth value, for use in an `if` or\n`while` 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 `or' and\n`and' always return one of their operands.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 860, "url": "https://docs.python.org/{python_version}/lib/node5.html"} {"title": "4.2 Built-in Module regex", "text": "node51.html node48.html node49.html node1.html node221.html\n---\n# 4.2 Built-in Module `regex`\nThis module provides regular expression matching operations similar to\nthose found in Emacs. It is always available.\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. E.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- 4.2.1 Regular Expressions (node51.html#SECTION00521000000000000000)\n4.2.2 Module Contents (node52.html#SECTION00522000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1813, "url": "https://docs.python.org/{python_version}/lib/node50.html"} {"title": "4.2.1 Regular Expressions", "text": "node52.html node50.html node50.html node1.html node221.html\n---\n## 4.2.1 Regular Expressions\nA regular expression (or RE) specifies a set of strings that matches\nit; the functions in this module let you check if a particular string\nmatches a given regular expression (or if a given regular expression\nmatches a particular string, which comes down to the same thing).\nRegular expressions can be concatenated to form new regular\nexpressions; if A and B are both regular expressions,\nthen AB is also an regular expression. If a string p\nmatches A and another string q matches B, the string pq\nwill match AB. Thus, complex expressions can easily be constructed\nfrom simpler ones like the primitives described here. For details of\nthe theory and implementation of regular expressions, consult almost\nany textbook about compiler construction.\nA brief explanation of the format of regular expressions follows.\nRegular expressions can contain both special and ordinary characters.\nOrdinary characters, like '`A`', '`a`', or '`0`', are\nthe simplest regular expressions; they simply match themselves. You\ncan concatenate ordinary characters, so '`last`' matches the\ncharacters 'last'. (In the rest of this section, we'll write RE's in\n`this special font`, usually without quotes, and strings to be\nmatched 'in single quotes'.)\nSpecial characters either stand for classes of ordinary characters, or\naffect how the regular expressions around them are interpreted.\nThe special characters are:\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 are indicated.\n---\nnode52.html node50.html node50.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1847, "url": "https://docs.python.org/{python_version}/lib/node51.html"} {"title": "4.2.2 Module Contents", "text": "node53.html node50.html node51.html node1.html node221.html\n---\n## 4.2.2 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---\nnode53.html node50.html node51.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 353, "url": "https://docs.python.org/{python_version}/lib/node52.html"} {"title": "4.3 Standard Module regsub", "text": "node54.html node48.html node52.html node1.html node221.html\n---\n# 4.3 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.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 285, "url": "https://docs.python.org/{python_version}/lib/node53.html"} {"title": "4.4 Built-in Module struct", "text": "node55.html node48.html node53.html node1.html node221.html\n---\n# 4.4 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:\nA format character may be preceded by an integral repeat count; e.g.\\\nthe format string `'4h'` means exactly the same as `'hhhh'`.\nC numbers are represented in the machine's native format and byte\norder, and properly aligned by skipping pad bytes if necessary\n(according to the rules used by the C compiler).\nExamples (all on a big-endian machine):\n```text\npack('hhl', 1, 2, 3) == '\\000\\001\\000\\002\\000\\000\\000\\003'\nunpack('hhl', '\\000\\001\\000\\002\\000\\000\\000\\003') == (1, 2, 3)\ncalcsize('hhl') == 8\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(More format characters are planned, e.g. `'s'` for character\narrays, upper case for unsigned variants, and a way to specify the\nbyte order, which is useful for [de]constructing network packets and\nreading/writing portable binary file formats like TIFF and AIFF.)\n---\nnode55.html node48.html node53.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1688, "url": "https://docs.python.org/{python_version}/lib/node54.html"} {"title": "5 Miscellaneous Services", "text": "node56.html lib.html node54.html node1.html node221.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` (node56.html#SECTION00610000000000000000)\n5.2 Standard Module `rand` (node57.html#SECTION00620000000000000000)\n5.3 Standard Module `whrandom` (node58.html#SECTION00630000000000000000)\n5.4 Built-in Module `array` (node59.html#SECTION00640000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 534, "url": "https://docs.python.org/{python_version}/lib/node55.html"} {"title": "5.1 Built-in Module math", "text": "node57.html node55.html node55.html node1.html node221.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:\n,\n,\n`acos( x )`,\n`asin( x )`,\n`atan( x )`,\n`atan2( x, y )`,\n`ceil( x )`,\n`cos( x )`,\n`cosh( x )`,\n`exp( x )`,\n`fabs( x )`,\n`floor( x )`,\n`fmod( x, y )`,\n`frexp( x )`,\n`hypot( x, y )`,\n`ldexp( x, y )`,\n`log( x )`,\n`log10( x )`,\n`modf( x )`,\n`pow( x, y )`,\n`sin( x )`,\n`sinh( x )`,\n`sqrt( x )`,\n`tan( x )`,\n`tanh( x )`.\n,\nNote that `frexp` and `modf` have a different call/return\npattern than their C equivalents: they take a single argument and\nreturn a pair of values, rather than returning their second return\nvalue through an `output parameter' (there is no such thing in Python).\nThe module also defines two mathematical constants:\n,\n,\n`pi` and `e`.\n,\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 894, "url": "https://docs.python.org/{python_version}/lib/node56.html"} {"title": "5.2 Standard Module rand", "text": "node58.html node55.html node56.html node1.html node221.html\n---\n# 5.2 Standard Module `rand`\nThis module implements a pseudo-random number\ngenerator with an interface similar to `rand()` in C. It defines\nthe following functions:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 256, "url": "https://docs.python.org/{python_version}/lib/node57.html"} {"title": "5.3 Standard Module whrandom", "text": "node59.html node55.html node57.html node1.html node221.html\n---\n# 5.3 Standard Module `whrandom`\nThis module implements a Wichmann-Hill pseudo-random number generator.\nIt defines the following functions:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 231, "url": "https://docs.python.org/{python_version}/lib/node58.html"} {"title": "5.4 Built-in Module array", "text": "node60.html node55.html node58.html node1.html node221.html\n---\n# 5.4 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:\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.\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---\nnode60.html node55.html node58.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1399, "url": "https://docs.python.org/{python_version}/lib/node59.html"} {"title": "2.1.2 Boolean Operations", "text": "node7.html node4.html node5.html node1.html node221.html\n---\n## 2.1.2 Boolean Operations\nThese are the Boolean operations, ordered by ascending priority:\n,\nNotes:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 190, "url": "https://docs.python.org/{python_version}/lib/node6.html"} {"title": "6 Generic Operating System Services", "text": "node61.html lib.html node59.html node1.html node221.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` (node61.html#SECTION00710000000000000000)\n6.2 Built-in Module `time` (node62.html#SECTION00720000000000000000)\n6.3 Standard Module `getopt` (node63.html#SECTION00730000000000000000)\n6.4 Standard Module `tempfile` (node64.html#SECTION00740000000000000000)\n6.5 Standard Module `errno` (node65.html#SECTION00750000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 792, "url": "https://docs.python.org/{python_version}/lib/node60.html"} {"title": "6.1 Standard Module os", "text": "node62.html node60.html node60.html node1.html node221.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\n`os` 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---\nnode62.html node60.html node60.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1697, "url": "https://docs.python.org/{python_version}/lib/node61.html"} {"title": "6.2 Built-in Module time", "text": "node63.html node60.html node61.html node1.html node221.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.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 of < 100 will typically be silently converted to\n1900 + year value. A -1 argument as daylight savings flag, passed to\n`mktime()` will usually result in the correct daylight savings\nstate to be filled in.\nThe module defines the following functions and data items:\n---\nnode63.html node60.html node61.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1946, "url": "https://docs.python.org/{python_version}/lib/node62.html"} {"title": "6.3 Standard Module getopt", "text": "node64.html node60.html node62.html node1.html node221.html\n---\n# 6.3 Standard Module `getopt`\nThis module helps scripts to parse the command line arguments in\n`sys.argv`.\nIt supports the same conventions as the Unix\n`getopt()`\nfunction (including the special meanings of arguments of the form\n`-' and `-'). Long options similar to those supported by\nGNU software may be used as well via an optional third argument.\nIt defines the function\n`getopt.getopt(args, options [, long_options])`\nand the exception\n`getopt.error`.\nThe first argument to\n`getopt()`\nis the argument list passed to the script with its first element\nchopped off (i.e.,\n`sys.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\n`getopt()`\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\n`getopt.error = 'getopt.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---\nnode64.html node60.html node62.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2936, "url": "https://docs.python.org/{python_version}/lib/node63.html"} {"title": "6.4 Standard Module tempfile", "text": "node65.html node60.html node63.html node1.html node221.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\n`fork()` and both parent and child continue to use\n`mktemp()`, 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---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 923, "url": "https://docs.python.org/{python_version}/lib/node64.html"} {"title": "6.5 Standard Module errno", "text": "node66.html node60.html node64.html node1.html node221.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.\nSymbols available can include:\n---\nnode66.html node60.html node64.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 542, "url": "https://docs.python.org/{python_version}/lib/node65.html"} {"title": "7 Optional Operating System Services", "text": "node67.html lib.html node65.html node1.html node221.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` (node67.html#SECTION00810000000000000000)\n7.2 Built-in Module `socket` (node68.html#SECTION00820000000000000000)\n- 7.2.1 Socket Objects (node69.html#SECTION00821000000000000000)\n7.2.2 Example (node70.html#SECTION00822000000000000000)\n7.3 Built-in Module `select` (node71.html#SECTION00830000000000000000)\n7.4 Built-in Module `thread` (node72.html#SECTION00840000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 843, "url": "https://docs.python.org/{python_version}/lib/node66.html"} {"title": "7.1 Built-in Module signal", "text": "node68.html node66.html node66.html node1.html node221.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:\n`SIGPIPE` 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\n`alarm()`, `getsignal()`, or `pause()`; only the main\nthread can set a new signal handler, and the main thread will be the\nonly one to receive signals (this is enforced by the Python signal\nmodule, even if the underlying thread implementation supports sending\nsignals to individual threads). This means that signals can't be used\nas a means of interthread communication. Use locks instead.\nThe variables defined in the signal module are:\nThe signal module defines the following functions:\n---\nnode68.html node66.html node66.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2561, "url": "https://docs.python.org/{python_version}/lib/node67.html"} {"title": "7.2 Built-in Module socket", "text": "node69.html node66.html node67.html node1.html node221.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 higer-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\n`AF_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.\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- 7.2.1 Socket Objects (node69.html#SECTION00821000000000000000)\n7.2.2 Example (node70.html#SECTION00822000000000000000)\n---\nnode69.html node66.html node67.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2266, "url": "https://docs.python.org/{python_version}/lib/node68.html"} {"title": "7.2.1 Socket Objects", "text": "node70.html node68.html node68.html node1.html node221.html\n---\n## 7.2.1 Socket Objects\n,\nSocket objects have the following methods. Except for\n`makefile()` these correspond to Unix system calls applicable to\nsockets.\nNote that there are no methods `read()` or `write()`; use\n`recv()` and `send()` without flags argument instead.\n---\nnode70.html node68.html node68.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 417, "url": "https://docs.python.org/{python_version}/lib/node69.html"} {"title": "2.1.3 Comparisons", "text": "node8.html node4.html node6.html node1.html node221.html\n---\n## 2.1.3 Comparisons\nComparison operations are supported by all objects. They all have the\nsame priority (which is higher than that of the Boolean operations).\nComparisons can be chained arbitrarily, 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:\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\n`not in`, are supported only by sequence types (below).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1233, "url": "https://docs.python.org/{python_version}/lib/node7.html"} {"title": "7.2.2 Example", "text": "node71.html node68.html node69.html node1.html node221.html\n---\n## 7.2.2 Example\nHere are two minimal example programs using the TCP/IP protocol: a\nserver that echoes all data that it receives back (servicing only one\nclient), and a client using it. Note that a server must perform the\nsequence `socket`, `bind`, `listen`, `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\n`accept`.\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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1241, "url": "https://docs.python.org/{python_version}/lib/node70.html"} {"title": "7.3 Built-in Module select", "text": "node72.html node66.html node70.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 234, "url": "https://docs.python.org/{python_version}/lib/node71.html"} {"title": "7.4 Built-in Module thread", "text": "node73.html node66.html node71.html node1.html node221.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 and supported on SGI IRIX 4.x and 5.x and Sun\nSolaris 2.x systems, as well as on systems that have a PTHREAD\nimplementation (e.g. KSR).\nIt defines the following constant and functions:\nLock objects have the following methods:\nCaveats:\n- Threads interact strangely with interrupts: the\n`KeyboardInterrupt` exception will be received by an arbitrary\nthread. (When the `signal` module is available, interrupts\nalways go to the main thread.)Calling `sys.exit()` or raising the `SystemExit` 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`,\n`select`) work as expected.)\n---\nnode73.html node66.html node71.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1162, "url": "https://docs.python.org/{python_version}/lib/node72.html"} {"title": "8 UNIX Specific Services", "text": "node74.html lib.html node72.html node1.html node221.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` (node74.html#SECTION00910000000000000000)\n8.2 Standard Module `posixpath` (node75.html#SECTION00920000000000000000)\n8.3 Built-in Module `pwd` (node76.html#SECTION00930000000000000000)\n8.4 Built-in Module `grp` (node77.html#SECTION00940000000000000000)\n8.5 Built-in module crypt (node78.html#SECTION00950000000000000000)\n8.6 Built-in Module `dbm` (node79.html#SECTION00960000000000000000)\n8.7 Built-in Module `gdbm` (node80.html#SECTION00970000000000000000)\n8.8 Built-in Module `termios` (node81.html#SECTION00980000000000000000)\n- 8.8.1 Example (node82.html#SECTION00981000000000000000)\n8.9 Standard Module `TERMIOS` (node83.html#SECTION00990000000000000000)\n8.10 Built-in Module `fcntl` (node84.html#SECTION009100000000000000000)\n8.11 Standard Module `posixfile` (node85.html#SECTION009110000000000000000)\n8.12 Built-in Module `syslog` (node86.html#SECTION009120000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1213, "url": "https://docs.python.org/{python_version}/lib/node73.html"} {"title": "8.1 Built-in Module posix", "text": "node75.html node73.html node73.html node1.html node221.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\n`posix` 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\n`posix`.\nThe descriptions below are very terse; refer to the\ncorresponding Unix manual entry for more information. Arguments\ncalled 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\n`posix.error`, described below.\nModule `posix` defines the following data items:\nIt defines the following functions and constants:\n---\nnode75.html node73.html node73.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1179, "url": "https://docs.python.org/{python_version}/lib/node74.html"} {"title": "8.2 Standard Module posixpath", "text": "node76.html node73.html node74.html node1.html node221.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---\nnode76.html node73.html node74.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 337, "url": "https://docs.python.org/{python_version}/lib/node75.html"} {"title": "8.3 Built-in Module pwd", "text": "node77.html node73.html node75.html node1.html node221.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:\n`pw_name`,\n`pw_passwd`,\n`pw_uid`,\n`pw_gid`,\n`pw_gecos`,\n`pw_dir`,\n`pw_shell`.\nThe uid and gid items are integers, all others are strings.\nAn exception is raised if the entry asked for cannot be found.\nIt defines the following items:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 587, "url": "https://docs.python.org/{python_version}/lib/node76.html"} {"title": "8.4 Built-in Module grp", "text": "node78.html node73.html node76.html node1.html node221.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:\n`gr_name`,\n`gr_passwd`,\n`gr_gid`,\n`gr_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.)\nAn exception is raised if the entry asked for cannot be found.\nIt defines the following items:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 701, "url": "https://docs.python.org/{python_version}/lib/node77.html"} {"title": "8.5 Built-in module crypt", "text": "node79.html node73.html node77.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 498, "url": "https://docs.python.org/{python_version}/lib/node78.html"} {"title": "8.6 Built-in Module dbm", "text": "node80.html node73.html node78.html node1.html node221.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\n`items()` 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@cnri.reston.va.us", "python_version": "1.4", "length": 550, "url": "https://docs.python.org/{python_version}/lib/node79.html"} {"title": "2.1.4 Numeric Types", "text": "node9.html node4.html node7.html node1.html node221.html\n---\n## 2.1.4 Numeric Types\nThere are three numeric types: plain integers, long integers, and\nfloating point numbers. Plain 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.\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.\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.\nComparisons between numbers of mixed type use the same rule.footnode.html#872\nThe functions `int()`, `long()` and `float()` 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):\n,\nNotes:\n---\n- Bit-string Operations on Integer Types (node9.html#SECTION00314100000000000000)\n---\nnode9.html node4.html node7.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1721, "url": "https://docs.python.org/{python_version}/lib/node8.html"} {"title": "8.7 Built-in Module gdbm", "text": "node81.html node73.html node79.html node1.html node221.html\n---\n# 8.7 Built-in Module `gdbm`\nThis module is nearly identical to the `dbm` module, but uses\nGDBM instead. Its interface is identical, and not repeated here.\nWarning: the file formats created by gdbm and dbm are incompatible.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 315, "url": "https://docs.python.org/{python_version}/lib/node80.html"} {"title": "8.8 Built-in Module termios", "text": "node82.html node73.html node80.html node1.html node221.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- 8.8.1 Example (node82.html#SECTION00981000000000000000)\n---\nnode82.html node73.html node80.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 892, "url": "https://docs.python.org/{python_version}/lib/node81.html"} {"title": "8.8.1 Example", "text": "node83.html node81.html node81.html node1.html node221.html\n---\n## 8.8.1 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@cnri.reston.va.us", "python_version": "1.4", "length": 704, "url": "https://docs.python.org/{python_version}/lib/node82.html"} {"title": "8.9 Standard Module TERMIOS", "text": "node84.html node73.html node82.html node1.html node221.html\n---\n# 8.9 Standard Module `TERMIOS`\nThis module defines the symbolic constants required to use the\n`termios` 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@cnri.reston.va.us", "python_version": "1.4", "length": 506, "url": "https://docs.python.org/{python_version}/lib/node83.html"} {"title": "8.10 Built-in Module fcntl", "text": "node85.html node73.html node83.html node1.html node221.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` and\n`sys/ioctl`. 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---\nnode85.html node73.html node83.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1191, "url": "https://docs.python.org/{python_version}/lib/node84.html"} {"title": "8.11 Standard Module posixfile", "text": "node86.html node73.html node84.html node1.html node221.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:\nIn addition the following modifiers can be added to the format:\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:\nIn addition the following modifiers can be added to the format:\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---\nnode86.html node73.html node84.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1957, "url": "https://docs.python.org/{python_version}/lib/node85.html"} {"title": "8.12 Built-in Module syslog", "text": "node87.html node73.html node85.html node1.html node221.html\n---\n# 8.12 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@cnri.reston.va.us", "python_version": "1.4", "length": 368, "url": "https://docs.python.org/{python_version}/lib/node86.html"} {"title": "9 The Python Debugger", "text": "node88.html lib.html node86.html node1.html node221.html\n---\n# 9 The Python Debugger\nThe module `pdb` defines an interactive source code debugger for\nPython programs. It supports setting 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\n`Pdb`. 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```\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 (node88.html#SECTION001010000000000000000)\n9.2 How It Works (node89.html#SECTION001020000000000000000)\n---\nnode88.html lib.html node86.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1766, "url": "https://docs.python.org/{python_version}/lib/node87.html"} {"title": "9.1 Debugger Commands", "text": "node89.html node87.html node87.html node1.html node221.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 (```|`'').\n\nEntering a blank line repeats the last command entered. Exception: if\nthe last command was a ```list`'' command, the next 11 lines are\nlisted.\n\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\n---\n\nnode89.html node87.html node87.html node1.html node221.html\n\nNext: 9.2 How It Works (node89.html)\nUp: 9 The Python Debugger (node87.html)\nPrevious: 9 The Python Debugger (node87.html)\n\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1453, "url": "https://docs.python.org/{python_version}/lib/node88.html"} {"title": "9.2 How It Works", "text": "node90.html node87.html node88.html node1.html node221.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)\nA trace function should return a new trace function or None.\nClass methods are accepted (and most useful!) as trace methods.\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---\nnode90.html node87.html node88.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 769, "url": "https://docs.python.org/{python_version}/lib/node89.html"} {"title": "Bit-string Operations on Integer Types", "text": "node10.html node8.html node8.html node1.html node221.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):\n,\nNotes:\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 761, "url": "https://docs.python.org/{python_version}/lib/node9.html"} {"title": "10 The Python Profiler", "text": "node91.html lib.html node89.html node1.html node221.html\n---\n# 10 The Python Profiler\nCopyright © 1994, by InfoSeek Corporation, all rights reserved.\nWritten by James Roskindfootnode.html#5552\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:\n`jar@netscape.com`. I won't promise any support. ...but\nI'd appreciate the feedback.\n---\n- 10.1 Introduction to the profiler (node91.html#SECTION001110000000000000000)\n10.2 How Is This Profiler Different From The Old Profiler? (node92.html#SECTION001120000000000000000)\n10.3 Instant Users Manual (node93.html#SECTION001130000000000000000)\n10.4 What Is Deterministic Profiling? (node94.html#SECTION001140000000000000000)\n10.5 Reference Manual (node95.html#SECTION001150000000000000000)\n- 10.5.1 The `Stats` Class (node96.html#SECTION001151000000000000000)\n10.6 Limitations (node97.html#SECTION001160000000000000000)\n10.7 Calibration (node98.html#SECTION001170000000000000000)\n10.8 Extensions - Deriving Better Profilers (node99.html#SECTION001180000000000000000)\n- 10.8.1 OldProfile Class (node100.html#SECTION001181000000000000000)\n10.8.2 HotProfile Class (node101.html#SECTION001182000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2757, "url": "https://docs.python.org/{python_version}/lib/node90.html"} {"title": "10.1 Introduction to the profiler", "text": "node92.html node90.html node90.html node1.html node221.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\n`profile` 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@cnri.reston.va.us", "python_version": "1.4", "length": 538, "url": "https://docs.python.org/{python_version}/lib/node91.html"} {"title": "10.2 How Is This Profiler Different From The Old Profiler?", "text": "node93.html node90.html node91.html node1.html node221.html\n---\n# 10.2 How Is This Profiler Different From The Old Profiler?\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@cnri.reston.va.us", "python_version": "1.4", "length": 311, "url": "https://docs.python.org/{python_version}/lib/node92.html"} {"title": "10.3 Instant Users Manual", "text": "node94.html node90.html node92.html node1.html node221.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```\nWhen you wish to review the profile, you should use the methods in the\n`pstats` 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\n`profile.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---\nnode94.html node90.html node92.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3555, "url": "https://docs.python.org/{python_version}/lib/node93.html"} {"title": "10.4 What Is Deterministic Profiling?", "text": "node95.html node90.html node93.html node1.html node221.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@cnri.reston.va.us", "python_version": "1.4", "length": 1809, "url": "https://docs.python.org/{python_version}/lib/node94.html"} {"title": "10.5 Reference Manual", "text": "node96.html node90.html node94.html node1.html node221.html\n---\n# 10.5 Reference Manual\nThe primary entry point for the profiler is the global function\n`profile.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- 10.5.1 The `Stats` Class (node96.html#SECTION001151000000000000000)\n---\nnode96.html node90.html node94.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 794, "url": "https://docs.python.org/{python_version}/lib/node95.html"} {"title": "10.5.1 The Stats Class", "text": "node97.html node95.html node95.html node1.html node221.html\n---\n## 10.5.1 The `Stats` Class\n---\nnode97.html node95.html node95.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 179, "url": "https://docs.python.org/{python_version}/lib/node96.html"} {"title": "10.6 Limitations", "text": "node98.html node90.html node96.html node1.html node221.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---\nnode98.html node90.html node96.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2333, "url": "https://docs.python.org/{python_version}/lib/node97.html"} {"title": "10.7 Calibration", "text": "node99.html node90.html node97.html node1.html node221.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---\nnode99.html node90.html node97.html node1.html node221.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2372, "url": "https://docs.python.org/{python_version}/lib/node98.html"} {"title": "10.8 Extensions - Deriving Better Profilers", "text": "node100.html node90.html node98.html node1.html node221.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\n`os.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- 10.8.1 OldProfile Class (node100.html#SECTION001181000000000000000)\n10.8.2 HotProfile Class (node101.html#SECTION001182000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1934, "url": "https://docs.python.org/{python_version}/lib/node99.html"} {"title": "Table of Contents", "text": "This file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\nGuido van Rossum\nAbstract\n## Table of Contents\nPython Reference Manual (ref0.html#HDT0)\n---", "python_version": "1.4", "length": 241, "url": "https://docs.python.org/{python_version}/ref/index.html"} {"title": "Table of Contents", "text": "This file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\nGuido van Rossum\nAbstract\n## Table of Contents\nPython Reference Manual (ref0.html#HDT0)\n---", "python_version": "1.4", "length": 241, "url": "https://docs.python.org/{python_version}/ref/ref.book.html"} {"title": "Python Reference Manual", "text": "Table of Contents (ref.book.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\nPython Reference Manual\n# Python Reference Manual\nGuido van Rossum\nCorporation for National Research Initiatives (CNRI)\n1895 Preston White Drive, Reston, Va 20191, USA\nE-mail: guido@cnri.reston.va.us (mailto:guido@cnri.reston.va.us),\nguido@python.org (mailto:guido@python.org)\nOctober 25, 1996\nRelease 1.4\nAbstract\nPython is a simple, yet powerful, interpreted programming\nlanguage that bridges the gap between C and shell programming, and is\nthus ideally suited for \"throw-away programming\" and rapid\nprototyping. Its syntax is put together from constructs borrowed from\na variety of other languages; most prominent are influences from ABC,\nC, Modula-3 and Icon.\nThe Python interpreter is easily extended with new functions\nand data types implemented in C. Python is also suitable as an\nextension language for highly customizable C applications such as\neditors or window managers.\nPython is available for various systems, amongst which most\ncommon flavors of UNIX (including Linux), the Apple Macintosh, MS-DOS,\nMS-Windows 3.1(1), Windows 95, Windows NT, and OS/2.\nThis reference manual describes the syntax and \"core semantics\"\nof the language. It is terse, but attempts to be exact and\ncomplete. The semantics of non-essential built-in object types and of\nthe built-in functions and modules are described in the Python\nLibrary Reference. For an informal introduction to the language,\nsee the Python Tutorial.\nCopyright © 1991-1995 by Stichting Mathematisch\nCentrum, Amsterdam, The Netherlands.\nAll Rights Reserved\nPermission to use, copy, modify, and distribute this software and\nits documentation 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 the copyright holders\nnot be used in advertising or publicity pertaining to distribution of\nthe software without specific, written prior permission.\nWhile CWI is the initial source for this software, a modified\nversion is made available by the Corporation for National Research\nInitiatives (CNRI) at the Internet address\nftp://ftp.python.org.\nSTICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS\nBE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY\nDAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,\nWHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,\nARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS\nSOFTWARE.\nTable of Contents (ref.book.html)\nNext Chapter (ref1.html)", "python_version": "1.4", "length": 2900, "url": "https://docs.python.org/{python_version}/ref/ref0.html"} {"title": "Chapter 1: Introduction", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref0.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 1: Introduction\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, 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_letter`s 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.\nTable of Contents (ref.book.html)\nNext Chapter (ref2.html)", "python_version": "1.4", "length": 4073, "url": "https://docs.python.org/{python_version}/ref/ref1.html"} {"title": "Chapter 2: Lexical analysis", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref1.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n```text\n\n```\n## Chapter 2: Lexical analysis\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.\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\\xad \\xad ; 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.\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)):\n\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 elif global not try\nbreak else if or while\nclass except import pass\ncontinue finally in print\n\ndef for is raise\ndel from lambda return\n```\n#### 2.3.2 Reserved classes of identifiers\nCertain classes of identifiers (besides keywords) have special meanings. These are:\nTable 1: Special Meanings of Identifiers (ref2.tbl_2.ps)\n```text\n\n---------------------------------------------\nForm Meaning\n---------------------------------------------\n_* Not imported by from module import *\n\n__*__\nSystem-defined name\n\n__*\nClass-private name mangling\n---------------------------------------------\n```\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: shortstring | longstring\nshortstring: \"'\" shortstringitem* \"'\" | '\"' shortstringitem* '\"'\nlongstring: \"'''\" longstringitem* \"'''\" | '\"\"\"' longstringitem* '\"\"\"'\nshortstringitem: shortstringchar | escapeseq\nlongstringitem: longstringchar | escapeseq\nshortstringchar: \nlongstringchar: \nescapeseq: \"\\\" \n```\nIn plain English: String literals can be enclosed in 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.\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 `\"`.)\nEscape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:\nTable 2: Escape Sequences (ref2.tbl_1.ps)\n```text\n\n------------------------------------------------------\nEscape Sequence Meaning\n------------------------------------------------------\n\n\\\nnewline\nIgnored\n\n\\\\\nBackslash (\n\\\n)\n\n\\'\nSingle quote (\n'\n)\n\n\\\"\nDouble quote (\n\"\n)\n\n\\a\nASCII Bell (BEL)\n\n\\b\nASCII Backspace (BS)\n\n\\f\nASCII Formfeed (FF)\n\n\\n\nASCII Linefeed (LF)\n\n\\r\nASCII Carriage Return (CR)\n\n\\t\nASCII Horizontal Tab (TAB)\n\n\\v\nASCII Vertical Tab (VT)\n\n\\\nooo\nASCII character with octal value\nooo\n\n\\x\nxx...\nASCII character with hex value\nxx...\n\n------------------------------------------------------\n```\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. It also helps a great deal for string literals used as regular expressions or otherwise passed to other modules that do their own escape handling.)\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.\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: digit+\nfraction: \".\" digit+\nexponent: (\"e\"|\"E\") [\"+\"|\"-\"] digit+\n```\nThe 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```\nTable of Contents (ref.book.html)\nNext Chapter (ref3.html)", "python_version": "1.4", "length": 15017, "url": "https://docs.python.org/{python_version}/ref/ref2.html"} {"title": "Chapter 3: Data model", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref2.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 3: Data model\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.\nNoneThis 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``other`. If no __cmp__ method is defined, class instances are compared by object identity (\"address\"). (Implementation note: due to limitations in the interpreter, exceptions raised by comparisons are ignored, and the outcome will be random in this case.)\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).`__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 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.``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.\nTable of Contents (ref.book.html)\nNext Chapter (ref4.html)", "python_version": "1.4", "length": 39812, "url": "https://docs.python.org/{python_version}/ref/ref3.html"} {"title": "Chapter 4: Execution model", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref3.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 4: Execution model\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) (ref4.html#FN1)\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! Notes:\nTable 3: Name Spaces for Various Code Blocks (ref4.tbl_1.ps)\n```text\n\n---------------------------------------------------------------------------------------------------\nCode block type Global name space Local name space Notes\n---------------------------------------------------------------------------------------------------\nModule n.s. for this module same as global\nScript (file or command) n.s. for\n__main__\nsame as global (1)\nInteractive command n.s. for\n__main__\nsame as global\nClass definition global n.s. of containing block new n.s.\nFunction body global n.s. of containing block new n.s.\nString passed to global n.s. of containing block local n.s. of containing (2), (3)\n\nexec\nstatement block\nString passed to\neval()\nglobal n.s. of caller local n.s. of caller (2), (3)\nFile read by\nexecfile()\nglobal n.s. of caller local n.s. of caller (2), (3)\nExpression read by\ninput\nglobal n.s. of caller local n.s. of caller\n---------------------------------------------------------------------------------------------------\n```\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) (ref4.html#FN2)\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 page45 (ref7.html#REF24886).\n---\n### Footnotes\nTable of Contents (ref.book.html)\nNext Chapter (ref5.html)", "python_version": "1.4", "length": 8324, "url": "https://docs.python.org/{python_version}/ref/ref4.html"} {"title": "Chapter 5: Expressions", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref4.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 5: Expressions\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 (ref3.html#REF19057). If both arguments are standard numeric types, the following coercions are applied:\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: identifier | literal | enclosure\nenclosure: parenth_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\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 page6 (ref2.html#REF40553) 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(In the original implementation, all literals in the same code block with the same type and value yield the same object.)\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 page12 (ref3.html#REF22319) (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 | ellipses\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\nellipses: \"...\"\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 ellipses slice item is the built-in Ellipses object. The conversion of a proper slice is a slice object (see page17 (ref3.html#REF18920)) 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 page48 (ref7.html#REF27502) 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 page48 (ref7.html#REF27502). 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)) orfloor((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:\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.(2) (ref5.html#FN2)\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 page48 (ref7.html#REF27502) 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).\nTable 4: Operator Precedence (ref5.tbl_1.ps)\n```text\n\n------------------------------------------------------------\n\nor\nBoolean OR\n\nand\nBoolean AND\n\nnot\nx\nBoolean NOT\n\nin, not in Membership tests\nis, is not Identity tests\n<, <=, >, >=, <>, !=, =\nComparisons\n\n|\nBitwise OR\n\n^\nBitwise XOR\n\n&\nBitwise AND\n\n<<, >>\nShifts\n\n+, -\nAddition and subtraction\n\n*, /, %\nMultiplication, division, remainder\n\n+x, -x Positive, negative\n~x\nBitwise not\n\nx.attribute Attribute reference\nx\n[\nindex\n] Subscription\n\nx\n[\nindex:index\n] Slicing\n\nf\n(\narguments\n, ...) Function call\n(\nexpressions\n. . .) Binding or tuple display\n[\nexpressions\n. . .] List display\n{\nkey:datum\n, . . .} Dictionary display\n`\nexpression\n` String conversion\n------------------------------------------------------------\n```\n---\n### Footnotes\nTable of Contents (ref.book.html)\nNext Chapter (ref6.html)", "python_version": "1.4", "length": 26164, "url": "https://docs.python.org/{python_version}/ref/ref5.html"} {"title": "Chapter 6: Simple statements", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref5.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 6: Simple statements\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| 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 page41 (ref6.html#REF25905)) on a line by itself. (Expression statements yielding None are not written, so that procedure calls do not cause any output.)\n### 6.2 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 page29 (ref5.html#REF30293) 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 page12. (ref3.html#REF22319))\nAssignment of an object to a target list is recursively defined as follows.\nAssignment of an object to a single target is recursively defined as follows.\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(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.3 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.4 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.5 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 file object named `stdout`in the built-in module `sys`. If no such object exists, or if it is not a writable file, a `RuntimeError` exception is raised. (The original implementation attempts to write to the system's original standard output instead, but this is not safe, and should be fixed.)\n### 6.6 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.\n`return` 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.7 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 page17 (ref3.html#REF27144) 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.8 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.9 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.(1) (ref6.html#FN1) It continues with the next cycle of the nearest enclosing loop.\n### 6.10 The `import` statement\n```text\n\nimport_stmt: \"import\" identifier (\",\" identifier)*\n| \"from\" identifier \"import\" identifier (\",\" identifier)*\n| \"from\" identifier \"import\" \"*\"\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 `from` form performs them once, with the first identifier specifying the module name.\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. This first looks for a built-in module definition, and if no built-in module if the given name is found, it searches a user-specified list of directories for a file whose name is the module name with extension `\".py\"`. (The current implementation uses the list of strings `sys.path` as the search path; it is initialized from the shell environment variable `$PYTHONPATH`, with an installation-dependent default.)\nIf a built-in module is found, its built-in initialization code is executed and step (1) is finished. If no matching file is found, `ImportError` is raised. If a file is found, it is parsed, yielding an executable code block. If a syntax error occurs, `SyntaxError` is raised. Otherwise, an empty module of the given name is created and inserted in the module table, and then the code block is executed in the context of this module. Exceptions during this execution terminate step (1).\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 may not occur in `global` statements in the same scope.\nThe `from` form with `*` may only occur in a module scope.\n(The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.)\n### 6.11 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.)\nNote: the `global` is a directive to the parser. Therefore, 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.12 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.\nHints: 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`.\n---\n### Footnotes\nTable of Contents (ref.book.html)\nNext Chapter (ref7.html)", "python_version": "1.4", "length": 13870, "url": "https://docs.python.org/{python_version}/ref/ref6.html"} {"title": "Chapter 7: Compound statements", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref6.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 7: Compound statements\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 page35 (ref5.html#REF18638) 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 page17 (ref3.html#REF27144)) identifying the point in the program where the exception occurred.\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.\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 page12 (ref3.html#REF22319))(1) (ref7.html#FN1):\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.(2) (ref7.html#FN2)\nFunction call semantics are described in section \"Calls\" on page31 (ref5.html#REF41934). When a user-defined function is called, first missing arguments for which a default value exists are supplied; then the arguments (a.k.a. actual parameters) are bound to the (formal) parameters, as follows:\nNote that the `variable length parameter list' feature only works at the top level of the parameter list; individual parameters use a model corresponding more closely to that of ordinary assignment. While the latter model is generally preferable, because of the greater type safety it offers (wrong-sized tuples aren't silently mistreated), variable length parameter lists are a sufficiently accepted practice in most programming languages that a compromise has been worked out. (And anyway, assignment has no equivalent for empty argument lists.)\nIt is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section \"Boolean operations\" on page35 (ref5.html#REF18638).\n### 7.6 Class definitions\nA class definition defines a class object (see section \"The standard type hierarchy\" on page12 (ref3.html#REF22319)):\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 page23 (ref4.html#REF17757)), 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.\n---\n### Footnotes\nTable of Contents (ref.book.html)\nNext Chapter (ref8.html)", "python_version": "1.4", "length": 13221, "url": "https://docs.python.org/{python_version}/ref/ref7.html"} {"title": "Chapter 8: Top-level components", "text": "Table of Contents (ref.book.html)\nPrevious Chapter (ref7.html)\nThis file was created with the fm2html filter.\nThe filter is copyright Norwegian Telecom Research and\nwas programmed by Jon Stephenson von Tetzchner.\n## Chapter 8: Top-level components\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### 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.\n```text\n\n```", "python_version": "1.4", "length": 2789, "url": "https://docs.python.org/{python_version}/ref/ref8.html"} {"title": "Footnotes", "text": "guido@cnri.reston.va.us", "python_version": "1.4", "length": 23, "url": "https://docs.python.org/{python_version}/tut/footnode.html"} {"title": "Python Tutorial", "text": "node1.html node1.html\n---\n# Python Tutorial\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\nOctober 25, 1996\nRelease 1.4\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 a simple, yet powerful programming language that bridges the\ngap between C and shell programming, and is thus ideally suited for\n``throw-away programming''\nand rapid prototyping. Its syntax is put\ntogether from constructs borrowed from a variety of other languages;\nmost prominent are influences from ABC, C, Modula-3 and Icon.\nThe Python interpreter is easily extended with new functions and data\ntypes implemented in C. Python is also suitable as an extension\nlanguage for highly customizable C applications such as editors or\nwindow managers.\nPython is available for various operating systems, amongst which\nseveral flavors of Unix, the Apple Macintosh, MS-DOS, Windows\n(3.1(1), '95 and NT flavors), OS/2, and others.\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 as the examples\nare self-contained, the tutorial can be read off-line as well.\nFor a description of standard objects and modules, see the Python\nLibrary Reference document. The Python Reference Manual gives\na more formal definition of the language.\n---\n- Contents (node1.html#SECTION00100000000000000000)\n1 Whetting Your Appetite (node2.html#SECTION00200000000000000000)\n- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)\n1.2 Introduction (node4.html#SECTION00220000000000000000)\n1.3 Where From Here (node5.html#SECTION00230000000000000000)\n2 Using the Python Interpreter (node6.html#SECTION00300000000000000000)\n- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)\n- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)\n2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)\n2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)\n- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)\n2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)\n2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)\n2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)\n2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)\n2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)\n- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)\n2.3.2 History Substitution (node18.html#SECTION00332000000000000000)\n2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)\n2.3.4 Commentary (node20.html#SECTION00334000000000000000)\n3 An Informal Introduction to Python (node21.html#SECTION00400000000000000000)\n- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)\n- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)\n3.1.2 Strings (node24.html#SECTION00412000000000000000)\n3.1.3 Lists (node25.html#SECTION00413000000000000000)\n3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)\n4 More Control Flow Tools (node27.html#SECTION00500000000000000000)\n- 4.1 If Statements (node28.html#SECTION00510000000000000000)\n4.2 For Statements (node29.html#SECTION00520000000000000000)\n4.3 The range() Function (node30.html#SECTION00530000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)\n4.5 Pass Statements (node32.html#SECTION00550000000000000000)\n4.6 Defining Functions (node33.html#SECTION00560000000000000000)\n5 Odds and Ends (node34.html#SECTION00600000000000000000)\n- 5.1 More on Lists (node35.html#SECTION00610000000000000000)\n5.2 The del statement (node36.html#SECTION00620000000000000000)\n5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)\n5.4 Dictionaries (node38.html#SECTION00640000000000000000)\n5.5 More on Conditions (node39.html#SECTION00650000000000000000)\n5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)\n6 Modules (node41.html#SECTION00700000000000000000)\n- 6.1 More on Modules (node42.html#SECTION00710000000000000000)\n6.2 Standard Modules (node43.html#SECTION00720000000000000000)\n6.3 The dir() function (node44.html#SECTION00730000000000000000)\n7 Output Formatting (node45.html#SECTION00800000000000000000)\n8 Errors and Exceptions (node46.html#SECTION00900000000000000000)\n- 8.1 Syntax Errors (node47.html#SECTION00910000000000000000)\n8.2 Exceptions (node48.html#SECTION00920000000000000000)\n8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)\n8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)\n8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)\n8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)\n9 Classes (node53.html#SECTION001000000000000000000)\n- 9.1 A word about terminology (node54.html#SECTION001010000000000000000)\n9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)\n9.3 A first look at classes (node56.html#SECTION001030000000000000000)\n- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)\n9.3.2 Class objects (node58.html#SECTION001032000000000000000)\n9.3.3 Instance objects (node59.html#SECTION001033000000000000000)\n9.3.4 Method objects (node60.html#SECTION001034000000000000000)\n9.4 Random remarks (node61.html#SECTION001040000000000000000)\n9.5 Inheritance (node62.html#SECTION001050000000000000000)\n- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)\n9.6 Odds and ends (node64.html#SECTION001060000000000000000)\n10 Recent Additions as of Release 1.1 (node65.html#SECTION001100000000000000000)\n- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)\n10.2 String Literals (node67.html#SECTION001120000000000000000)\n- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)\n10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)\n10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)\n10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)\n10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)\n- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)\n10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)\n10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)\n- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)\n10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)\n10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)\n- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)\n10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)\n10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)\n10.7 Regular Expressions (node85.html#SECTION001170000000000000000)\n10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)\n10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)\n10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)\n10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)\n- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)\n10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)\n10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)\n11 New in Release 1.2 (node93.html#SECTION001200000000000000000)\n- 11.1 New Class Features (node94.html#SECTION001210000000000000000)\n11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)\n11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)\n11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)\n- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)\n11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)\n11.5 Documentation Strings (node100.html#SECTION001250000000000000000)\n11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)\n11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)\n11.8 Miscellaneous (node103.html#SECTION001280000000000000000)\n12 New in Release 1.3 (node104.html#SECTION001300000000000000000)\n- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)\n12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)\n12.3 Other Language Changes (node107.html#SECTION001330000000000000000)\n12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)\n12.5 Library Changes (node109.html#SECTION001350000000000000000)\n12.6 Other Changes (node110.html#SECTION001360000000000000000)\n13 New in Release 1.4 (node111.html#SECTION001400000000000000000)\n- 13.1 Language Changes (node112.html#SECTION001410000000000000000)\n13.2 Run-time Changes (node113.html#SECTION001420000000000000000)\n13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)\n13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)\nAbout this document ... (node116.html#SECTION001500000000000000000)\n---\nnode1.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 10704, "url": "https://docs.python.org/{python_version}/tut/index.html"} {"title": "Contents", "text": "node2.html tut.html tut.html\n---\n## Contents\n- 1 Whetting Your Appetite (node2.html#SECTION00200000000000000000)\n- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)\n1.2 Introduction (node4.html#SECTION00220000000000000000)\n1.3 Where From Here (node5.html#SECTION00230000000000000000)\n2 Using the Python Interpreter (node6.html#SECTION00300000000000000000)\n- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)\n- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)\n2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)\n2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)\n- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)\n2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)\n2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)\n2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)\n2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)\n2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)\n- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)\n2.3.2 History Substitution (node18.html#SECTION00332000000000000000)\n2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)\n2.3.4 Commentary (node20.html#SECTION00334000000000000000)\n3 An Informal Introduction to Python (node21.html#SECTION00400000000000000000)\n- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)\n- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)\n3.1.2 Strings (node24.html#SECTION00412000000000000000)\n3.1.3 Lists (node25.html#SECTION00413000000000000000)\n3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)\n4 More Control Flow Tools (node27.html#SECTION00500000000000000000)\n- 4.1 If Statements (node28.html#SECTION00510000000000000000)\n4.2 For Statements (node29.html#SECTION00520000000000000000)\n4.3 The range() Function (node30.html#SECTION00530000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)\n4.5 Pass Statements (node32.html#SECTION00550000000000000000)\n4.6 Defining Functions (node33.html#SECTION00560000000000000000)\n5 Odds and Ends (node34.html#SECTION00600000000000000000)\n- 5.1 More on Lists (node35.html#SECTION00610000000000000000)\n5.2 The del statement (node36.html#SECTION00620000000000000000)\n5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)\n5.4 Dictionaries (node38.html#SECTION00640000000000000000)\n5.5 More on Conditions (node39.html#SECTION00650000000000000000)\n5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)\n6 Modules (node41.html#SECTION00700000000000000000)\n- 6.1 More on Modules (node42.html#SECTION00710000000000000000)\n6.2 Standard Modules (node43.html#SECTION00720000000000000000)\n6.3 The dir() function (node44.html#SECTION00730000000000000000)\n7 Output Formatting (node45.html#SECTION00800000000000000000)\n8 Errors and Exceptions (node46.html#SECTION00900000000000000000)\n- 8.1 Syntax Errors (node47.html#SECTION00910000000000000000)\n8.2 Exceptions (node48.html#SECTION00920000000000000000)\n8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)\n8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)\n8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)\n8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)\n9 Classes (node53.html#SECTION001000000000000000000)\n- 9.1 A word about terminology (node54.html#SECTION001010000000000000000)\n9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)\n9.3 A first look at classes (node56.html#SECTION001030000000000000000)\n- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)\n9.3.2 Class objects (node58.html#SECTION001032000000000000000)\n9.3.3 Instance objects (node59.html#SECTION001033000000000000000)\n9.3.4 Method objects (node60.html#SECTION001034000000000000000)\n9.4 Random remarks (node61.html#SECTION001040000000000000000)\n9.5 Inheritance (node62.html#SECTION001050000000000000000)\n- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)\n9.6 Odds and ends (node64.html#SECTION001060000000000000000)\n10 Recent Additions as of Release 1.1 (node65.html#SECTION001100000000000000000)\n- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)\n10.2 String Literals (node67.html#SECTION001120000000000000000)\n- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)\n10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)\n10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)\n10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)\n10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)\n- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)\n10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)\n10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)\n- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)\n10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)\n10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)\n- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)\n10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)\n- Map. (node81.html#SECTION001152100000000000000)\nFilter. (node82.html#SECTION001152200000000000000)\nReduce. (node83.html#SECTION001152300000000000000)\n10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)\n10.7 Regular Expressions (node85.html#SECTION001170000000000000000)\n10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)\n10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)\n10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)\n10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)\n- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)\n10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)\n10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)\n11 New in Release 1.2 (node93.html#SECTION001200000000000000000)\n- 11.1 New Class Features (node94.html#SECTION001210000000000000000)\n11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)\n11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)\n11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)\n- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)\n11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)\n11.5 Documentation Strings (node100.html#SECTION001250000000000000000)\n11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)\n11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)\n11.8 Miscellaneous (node103.html#SECTION001280000000000000000)\n12 New in Release 1.3 (node104.html#SECTION001300000000000000000)\n- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)\n12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)\n12.3 Other Language Changes (node107.html#SECTION001330000000000000000)\n12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)\n12.5 Library Changes (node109.html#SECTION001350000000000000000)\n12.6 Other Changes (node110.html#SECTION001360000000000000000)\n13 New in Release 1.4 (node111.html#SECTION001400000000000000000)\n- 13.1 Language Changes (node112.html#SECTION001410000000000000000)\n13.2 Run-time Changes (node113.html#SECTION001420000000000000000)\n13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)\n13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)\nAbout this document ... (node116.html#SECTION001500000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 8062, "url": "https://docs.python.org/{python_version}/tut/node1.html"} {"title": "2.2 The Interpreter and its Environment", "text": "node11.html node6.html node9.html node1.html\n---\n# 2.2 The Interpreter and its Environment\n---\n- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)\n2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)\n2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)\n2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)\n2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 483, "url": "https://docs.python.org/{python_version}/tut/node10.html"} {"title": "11.5 Documentation Strings", "text": "node101.html node93.html node99.html node1.html\n---\n# 11.5 Documentation Strings\nA variety of objects now have a new attribute, `__doc__`, which\nis supposed to contain a documentation string (if no documentation is\npresent, the attribute is `None`). New syntax, compatible with\nthe old interpreter, allows for convenient initialization of the\n`__doc__` attribute of modules, classes and functions by placing\na string literal by itself as the first statement in the suite. It\nmust be a literal -- an expression yielding a string object is not\naccepted as a documentation string, since future tools may need to\nderive documentation from source by parsing.\nHere is a hypothetical, amply documented module called `Spam`:\n```text\n\"\"\"Spam operations.\n\nThis module exports two classes, a function and an exception:\n\nclass Spam: full Spam functionality --- three can sizes\nclass SpamLight: limited Spam functionality --- only one can size\n\ndef open(filename): open a file and return a corresponding Spam or\nSpamLight object\n\nGoneOff: exception raised for errors; should never happen\n\nNote that it is always possible to convert a SpamLight object to a\nSpam object by a simple method call, but that the reverse operation is\ngenerally costly and may fail for a number of reasons.\n\"\"\"\n\nclass SpamLight:\n\"\"\"Limited spam functionality.\n\nSupports a single can size, no flavor, and only hard disks.\n\"\"\"\n\ndef __init__(self, size=12):\n\"\"\"Construct a new SpamLight instance.\n\nArgument is the can size.\n\"\"\"\n# etc.\n\n# etc.\n\nclass Spam(SpamLight):\n\"\"\"Full spam functionality.\n\nSupports three can sizes, two flavor varieties, and all floppy\ndisk formats still supported by current hardware.\n\"\"\"\n\ndef __init__(self, size1=8, size2=12, size3=20):\n\"\"\"Construct a new Spam instance.\n\nArguments are up to three can sizes.\n\"\"\"\n# etc.\n\n# etc.\n\ndef open(filename = \"/dev/null\"):\n\"\"\"Open a can of Spam.\n\nArgument must be an existing file.\n\"\"\"\n# etc.\n\nclass GoneOff:\n\"\"\"Class used for Spam exceptions.\n\nThere shouldn't be any.\n\"\"\"\npass\n```\nAfter executing ```import Spam`'', the following expressions\nreturn the various documentation strings from the module:\n```text\nSpam.__doc__\nSpam.SpamLight.__doc__\nSpam.SpamLight.__init__.__doc__\nSpam.Spam.__doc__\nSpam.Spam.__init__.__doc__\nSpam.open.__doc__\nSpam.GoneOff.__doc__\n```\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).\nIn this release, few of the built-in or standard functions and modules\nhave documentation strings.\n---\nnode101.html node93.html node99.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 4092, "url": "https://docs.python.org/{python_version}/tut/node100.html"} {"title": "11.6 Customizing Import and Built-Ins", "text": "node102.html node93.html node100.html node1.html\n---\n# 11.6 Customizing Import and Built-Ins\nIn preparation for a ``restricted execution mode'' which will be\nusable to run code received from an untrusted source (such as a WWW\nserver or client), the mechanism by which modules are imported has\nbeen redesigned. It is now possible to provide your own function\n`__import__` which is called whenever an `import` statement\nis executed. There's a built-in function `__import__` which\nprovides the default implementation, but more interesting, the various\nsteps it takes are available separately from the new built-in module\n`imp`. (See the section on `imp` in the Library Reference\nManual for more information on this module -- it also contains a\ncomplete example of how to write your own `__import__` function.)\nWhen you do `dir()` in a fresh interactive interpreter you will\nsee another ``secret'' object that's present in every module:\n`__builtins__`. This is either a dictionary or a module\ncontaining the set of built-in objects used by functions defined in\ncurrent module. Although normally all modules are initialized with a\nreference to the same dictionary, it is now possible to use a\ndifferent set of built-ins on a per-module basis. Together with the\nfact that the `import` statement uses the `__import__`\nfunction it finds in the importing modules' dictionary of built-ins,\nthis forms the basis for a future restricted execution mode.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1468, "url": "https://docs.python.org/{python_version}/tut/node101.html"} {"title": "11.7 Python and the World-Wide Web", "text": "node103.html node93.html node101.html node1.html\n---\n# 11.7 Python and the World-Wide Web\nThere is a growing number of modules available for writing WWW tools.\nThe previous release already sported modules `gopherlib`,\n`ftplib`, `httplib` and `urllib` (which unifies the\nother three) for accessing data through the commonest WWW protocols.\nThis release also provides `cgi`, to ease the writing of\nserver-side scripts that use the Common Gateway Interface protocol,\nsupported by most WWW servers. The module `urlparse` provides\nprecise parsing of a URL string into its components (address scheme,\nnetwork location, path, parameters, query, and fragment identifier).\nA rudimentary, parser for HTML files is available in the module\n`htmllib`. It currently supports a subset of HTML 1.0 (if you\nbring it up to date, I'd love to receive your fixes!). Unfortunately\nPython seems to be too slow for real-time parsing and formatting of\nHTML such as required by interactive WWW browsers -- but it's good\nenough to write a ``robot'' (an automated WWW browser that searches\nthe web for information).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1115, "url": "https://docs.python.org/{python_version}/tut/node102.html"} {"title": "11.8 Miscellaneous", "text": "node104.html node93.html node102.html node1.html\n---\n# 11.8 Miscellaneous\n- The `socket` module now exports all the needed constants used for\nsocket operations, such as `SO_BROADCAST`.The functions `popen()` and `fdopen()` in the `os`\nmodule now follow the pattern of the built-in function `open()`:\nthe default mode argument is `'r'` and the optional third\nargument specifies the buffer size, where `0` means unbuffered,\n`1` means line-buffered, and any larger number means the size of\nthe buffer in bytes.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 535, "url": "https://docs.python.org/{python_version}/tut/node103.html"} {"title": "12 New in Release 1.3", "text": "node105.html tut.html node103.html node1.html\n---\n# 12 New in Release 1.3\nThis chapter describes yet more recent additions to the Python\nlanguage and library.\n---\n- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)\n12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)\n12.3 Other Language Changes (node107.html#SECTION001330000000000000000)\n12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)\n12.5 Library Changes (node109.html#SECTION001350000000000000000)\n12.6 Other Changes (node110.html#SECTION001360000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 626, "url": "https://docs.python.org/{python_version}/tut/node104.html"} {"title": "12.1 Keyword Arguments", "text": "node106.html node104.html node104.html node1.html\n---\n# 12.1 Keyword Arguments\nFunctions and methods written in Python can now 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 the form: zero or more\npositional arguments followed by zero or more keyword arguments, where\nthe keywords must be chosen from the formal parameter names. It's not\nimportant whether a formal parameter has a default value or not. No\nargument must receive a value more than once -- formal parameter names\ncorresponding to positional arguments cannot be used as keywords in\nthe same calls.\nNote that no special syntax is required to allow a function to be\ncalled with keyword arguments. The additional costs incurred by\nkeyword arguments are only present when a call uses them.\n(As far as I know, these rules are exactly the same as used by\nModula-3, even if they are enforced by totally different means. This\nis intentional.)\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` which\nreceives a tuple containing the positional arguments beyond the formal\nparameter list. (`* name` must occur before\n`** name`.) For example, 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```\nConsequences of this change include:\n- The built-in function `apply()` now has an optional third\nargument, which is a dictionary specifying any keyword arguments to be\npassed. For example,\n```text\napply(parrot, (), {'voltage': 20, 'action': 'voomm'})\n```\nis equivalent to\n```text\nparrot(voltage=20, action='voomm')\n```\nThere is also a mechanism for functions and methods defined in an\nextension module (i.e., implemented in C or C++) to receive a\ndictionary of their keyword arguments. By default, such functions do\nnot accept keyword arguments, since the argument names are not\navailable to the interpreter.In the effort of implementing keyword arguments, function and\nespecially method calls have been sped up significantly -- for a\nmethod with ten formal parameters, the call overhead has been cut in\nhalf; for a function with one formal parameters, the overhead has been\nreduced by a third.The format of `.pyc` files has changed (again).The `access` statement has been disabled. The syntax is still\nrecognized but no code is generated for it. (There were some\nunpleasant interactions with changes for keyword arguments, and my\nplan is to get rid of `access` altogether in favor of a different\napproach.)\n---\nnode106.html node104.html node104.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 4167, "url": "https://docs.python.org/{python_version}/tut/node105.html"} {"title": "12.2 Changes to the WWW and Internet tools", "text": "node107.html node104.html node105.html node1.html\n---\n# 12.2 Changes to the WWW and Internet tools\n- The `htmllib` module has been rewritten in an incompatible\nfashion. The new version is considerably more complete (HTML 2.0\nexcept forms, but including all ISO-8859-1 entity definitions), and\neasy to use. Small changes to `sgmllib` have also been made, to\nbetter match the tokenization of HTML as recognized by other web\ntools.A new module `formatter` has been added, for use with the new\n`htmllib` module.The `urllib`and `httplib` modules have been changed somewhat\nto allow overriding unknown URL types and to support authentication.\nThey now use `mimetools.Message` instead of `rfc822.Message`\nto parse headers. The `endrequest()` method has been removed\nfrom the HTTP class since it breaks the interaction with some servers.The `rfc822.Message` class has been changed to allow a flag to be\npassed in that says that the file is unseekable.The `ftplib` module has been fixed to be (hopefully) more robust\non Linux.Several new operations that are optionally supported by servers have\nbeen added to `nntplib`: `xover`, `xgtitle`,\n`xpath` and `date`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1178, "url": "https://docs.python.org/{python_version}/tut/node106.html"} {"title": "12.3 Other Language Changes", "text": "node108.html node104.html node106.html node1.html\n---\n# 12.3 Other Language Changes\n- The `raise` statement now takes an optional argument which\nspecifies the traceback to be used when printing the exception's stack\ntrace. This must be a traceback object, such as found in\n`sys.exc_traceback`. When omitted or given as `None`, the\nold behavior (to generate a stack trace entry for the current stack\nframe) is used.The tokenizer is now more tolerant of alien whitespace. Control-L in\nthe leading whitespace of a line resets the column number to zero,\nwhile Control-R just before the end of the line is ignored.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 637, "url": "https://docs.python.org/{python_version}/tut/node107.html"} {"title": "12.4 Changes to Built-in Operations", "text": "node109.html node104.html node107.html node1.html\n---\n# 12.4 Changes to Built-in Operations\n- For file objects, `f .read(0)` and\n`f .readline(0)` now return an empty string rather than\nreading an unlimited number of bytes. For the latter, omit the\nargument altogether or pass a negative value.A new system variable, `sys.platform`, has been added. It\nspecifies the current platform, e.g. `sunos5` or `linux1`.The built-in functions `input()` and `raw_input()` now use\nthe GNU readline library when it has been configured (formerly, only\ninteractive input to the interpreter itself was read using GNU\nreadline). The GNU readline library provides elaborate line editing\nand history. The Python debugger (`pdb`) is the first\nbeneficiary of this change.Two new built-in functions, `globals()` and `locals()`,\nprovide access to dictionaries containming current global and local\nvariables, respectively. (These augment rather than replace\n`vars()`, which returns the current local variables when called\nwithout an argument, and a module's global variables when called with\nan argument of type module.)The built-in function `compile()` now takes a third possible\nvalue for the kind of code to be compiled: specifying `'single'`\ngenerates code for a single interactive statement, which prints the\noutput of expression statements that evaluate to something else than\n`None`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1393, "url": "https://docs.python.org/{python_version}/tut/node108.html"} {"title": "12.5 Library Changes", "text": "node110.html node104.html node108.html node1.html\n---\n# 12.5 Library Changes\n- There are new module `ni` and `ihooks` that support\nimporting modules with hierarchical names such as `A.B.C`. This\nis enabled by writing `import ni; ni.ni()` at the very top of the\nmain program. These modules are amply documented in the Python\nsource.The module `rexec` has been rewritten (incompatibly) to define a\nclass and to use `ihooks`.The `string.split()` and `string.splitfields()` functions\nare now the same function (the presence or absence of the second\nargument determines which operation is invoked); similar for\n`string.join()` and `string.joinfields()`.The `Tkinter` module and its helper `Dialog` have been\nrevamped to use keyword arguments. Tk 4.0 is now the standard. A new\nmodule `FileDialog` has been added which implements standard file\nselection dialogs.The optional built-in modules `dbm` and `gdbm` are more\ncoordinated -- their `open()` functions now take the same values\nfor their flag argument, and the flag and mode\nargument have default values (to open the database for reading only,\nand to create the database with mode `0666` minuse the umask,\nrespectively). The memory leaks have finally been fixed.A new dbm-like module, `bsddb`, has been added, which uses the\nBSD DB package's hash method.A portable (though slow) dbm-clone, implemented in Python, has been\nadded for systems where none of the above is provided. It is aptly\ndubbed `dumbdbm`.The module `anydbm` provides a unified interface to `bsddb`,\n`gdbm`, `dbm`, and `dumbdbm`, choosing the first one\navailable.A new extension module, `binascii`, provides a variety of\noperations for conversion of text-encoded binary data.There are three new or rewritten companion modules implemented in\nPython that can encode and decode the most common such formats:\n`uu` (uuencode), `base64` and `binhex`.A module to handle the MIME encoding quoted-printable has also been\nadded: `quopri`.The parser module (which provides an interface to the Python parser's\nabstract syntax trees) has been rewritten (incompatibly) by Fred\nDrake. It now lets you change the parse tree and compile the result!The `syslog` module has been upgraded and documented.\n---\nnode110.html node104.html node108.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2278, "url": "https://docs.python.org/{python_version}/tut/node109.html"} {"title": "2.2.1 Error Handling", "text": "node12.html node10.html node10.html node1.html\n---\n## 2.2.1 Error Handling\nWhen an error occurs, the interpreter prints an error\nmessage and a stack trace. In interactive mode, it then returns to\nthe primary prompt; when input came from a file, it exits with a\nnonzero exit status after printing\nthe stack trace. (Exceptions handled by an except clause in a\ntry statement are not errors in this context.) Some errors are\nunconditionally fatal and cause an exit with a nonzero exit; this\napplies to internal inconsistencies and some cases of running out of\nmemory. All error messages are written to the standard error stream;\nnormal output from the executed commands is written to standard\noutput.\nTyping the interrupt character (usually Control-C or DEL) to the\nprimary or secondary prompt cancels the input and returns to the\nprimary prompt.footnode.html#69\nTyping an interrupt while a command is executing raises the\nKeyboardInterrupt exception, which may be handled by a try\nstatement.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1016, "url": "https://docs.python.org/{python_version}/tut/node11.html"} {"title": "12.6 Other Changes", "text": "node111.html node104.html node109.html node1.html\n---\n# 12.6 Other Changes\n- The dynamic module loader recognizes the fact that different filenames\npoint to the same shared library and loads the library only once, so\nyou can have a single shared library that defines multiple modules.\n(SunOS / SVR4 style shared libraries only.)Jim Fulton's ``abstract object interface'' has been incorporated into\nthe run-time API. For more detailes, read the files\n`Include/abstract.h` and `Objects/abstract.c`.The Macintosh version is much more robust now.Numerous things I have forgotten or that are so obscure no-one will\nnotice them anyway :-)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 660, "url": "https://docs.python.org/{python_version}/tut/node110.html"} {"title": "13 New in Release 1.4", "text": "node112.html tut.html node110.html node1.html\n---\n# 13 New in Release 1.4\nThis chapter describes the major additions to the Python language and\nlibrary in version 1.4. Many minor changes are not listed here;\nit is recommended to read the file `Misc/NEWS` in the Python\nsource distribution for a complete listing of changes. In particular,\nchanges that only affect C programmers or the build and installation\nprocess are not described in this chapter (the new installation\nlay-out is explained below under `sys.prefix` though).\n---\n- 13.1 Language Changes (node112.html#SECTION001410000000000000000)\n13.2 Run-time Changes (node113.html#SECTION001420000000000000000)\n13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)\n13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 844, "url": "https://docs.python.org/{python_version}/tut/node111.html"} {"title": "13.1 Language Changes", "text": "node113.html node111.html node111.html node1.html\n---\n# 13.1 Language Changes\n- Power operator. `x**y` is equivalent to `pow(x, y)`.\nThis operator binds more tightly than `*`, `/` or `%`,\nand binds from right to left when repeated or combined with unary\noperators. For example, `x**y**z` is equivalent to\n`x**(y**z)`, and `-x**y` is `-(x**y)`.Complex numbers. Imaginary literals are writen with a `'j'`\nsuffix (`'J'` is allowed as well.) Complex numbers with a nonzero\nreal component are written as `( real + imag j)`. You\ncan also use the new built-in function `complex()` which takes\none or two arguments: `complex(x)` is equivalent to `x +\n0j`, and `complex(x, y)` is `x + y*0j`. For example,\n`1j**2` yields `complex(-1.0)` (which is another way of\nsaying ``the real value 1.0 represented as a complex number.''\nComplex numbers are always represented as two floating point numbers,\nthe real and imaginary part.\nTo extract these parts from a complex number `z`,\nuse `z.real` and `z.imag`. The conversion functions to\nfloating point and integer (`float()`, `int()` and\n`long()`) don't work for complex numbers -- there is no one\ncorrect way to convert a complex number to a real number. Use\n`abs(z)` to get its magnitude (as a float) or `z.real` to\nget its real part.\nModule `cmath` provides versions of all math functions that take\ncomplex arguments and return complex results. (Module `math`\nonly supports real numbers, so that `math.sqrt(-1)` still raises\na `ValueError` exception. Numerical experts agree that this is\nthe way it should be.)New indexing syntax. It is now possible to use a tuple as an indexing\nexpression for a mapping object without parenthesizing it,\ne.g. `x[1, 2, 3]` is equivalent to `x[(1, 2, 3)]`.New slicing syntax. In support of the Numerical Python extension\n(distributed independently), slice indices of the form\n`x[lo:hi:stride]` are possible, multiple slice indices separated by\ncommas are allowed, and an index position may be replaced by an ellipsis,\nas follows: `x[a, ..., z]`. There's also a new built-in function\n`slice(lo, hi, stride)` and a new built-in object\n`Ellipsis`, which yield the same effect without using special\nsyntax. None of the standard sequence types support indexing with\nslice objects or ellipses yet.\nNote that when this new slicing syntax is used, the mapping interface\nwill be used, not the sequence interface. In particular, when a\nuser-defined class instance is sliced using this new slicing syntax,\nits `__getitem__` method is invoked -- the\n`__getslice__` method is only invoked when a single old-style\nslice is used, i.e. `x[lo:hi]`, with possible omission of\n`lo` and/or `hi`. Some examples:\n```text\nx[0:10:2] -> slice(0, 10, 2)\nx[:2:] -> slice(None, 2, None)\nx[::-1] -> slice(None, None, -1)\nx[::] -> slice(None, None, None)\nx[1, 2:3] -> (1, slice(2, 3, None))\nx[1:2, 3:4] -> (slice(1, 2, None), slice(3, 4, None))\nx[1:2, ..., 3:4] -> (slice(1, 2, None), Ellipsis,\nslice(3, 4, None))\n```\nFor more help with this you are referred to the matrix-sig.The `access` statement is now truly gone; `access` is no\nlonger a reserved word. This saves a few cycles here and there.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\n`evalfile()` does not consider the classname of the invoking\nclass to be the current class; this is similar to the effect of the\n`global` statement, the effect of which is likewise restricted to\ncode that is byte-compiled together. The same restriction applies to\n`getattr()`, `setattr()` and `delattr()`, as well as\nwhen referencing `__dict__` directly.\nHere's an example of a class that implements its own\n`__getattr__` and `__setattr__` methods and stores all\nattributes in a private variable, in a way that works in Python 1.4 as\nwell as in previous versions:\n```text\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```\nWarning: this is an experimental feature. To avoid all\npotential problems, refrain from using identifiers starting with\ndouble underscore except for predefined uses like `__init__`. To\nuse private names while maintaining future compatibility: refrain from\nusing the same private name in classes related via subclassing; avoid\nexplicit (manual) mangling/unmangling; and assume that at some point\nin the future, leading double underscore will revert to being just a\nnaming convention. Discussion on extensive compile-time declarations\nare currently underway, and it is impossible to predict what solution\nwill eventually be chosen for private names. Double leading\nunderscore is still a candidate, of course -- just not the only one.\nIt is placed in the distribution in the belief that it is useful, and\nso that widespread experience with its use can be gained. It will not\nbe removed without providing a better solution and a migration path.\n---\nnode113.html node111.html node111.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 6458, "url": "https://docs.python.org/{python_version}/tut/node112.html"} {"title": "13.2 Run-time Changes", "text": "node114.html node111.html node112.html node1.html\n---\n# 13.2 Run-time Changes\n- New built-in function `list()` converts any sequence to a new list.\nNote that when the argument is a list, the return value is a fresh\ncopy, similar to what would be returned by `a[:]`.Improved syntax error message. Syntax errors detected by the code\ngeneration phase of the Python bytecode compiler now include a line\nnumber. The line number is appended in parentheses. It is suppressed\nif the error occurs in line 1 (this usually happens in interactive\nuse).Different exception raised.\nUnrecognized keyword arguments now raise a `TypeError` exception\nrather than `KeyError`.Exceptions in `__del__` methods. When a `__del__` method\nraises an exception, a warning is written to `sys.stderr` and the\nexception is ignored. Formerly, such exceptions were ignored without\nwarning. (Propagating the exception is not an option since it it is\ninvoked from an object finalizer, which cannot return any kind of\nstatus or error.) (Buglet: The new behavior, while needed in order to\ndebug failing `__del__` methods, is occasionally annoying,\nbecause if affects the program's standard error stream. It honors\nassignments to `sys.stderr`, so it can be redirected from within\na program if desired.)You can now discover from which file (if any) a module was loaded by\ninspecting its `__file__` attribute. This attribute is not\npresent for built-in or frozen modules. It points to the shared\nlibrary file for dynamically loaded modules. (Buglet: this may be a\nrelative path and is stored in the `.pyc` file on compilation.\nIf you manipulate the current directory with `os.chdir()` or move\n`.pyc` files around, the value may be incorrect.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1730, "url": "https://docs.python.org/{python_version}/tut/node113.html"} {"title": "13.3 New or Updated Modules", "text": "node115.html node111.html node113.html node1.html\n---\n# 13.3 New or Updated Modules\n- New built-in module `operator`. While undocumented, the concept\nis real simply: `operator.__add__(x, y)` does exactly the same\nthing as `x+y` (for all types -- built-in, user-defined,\nextension-defined). As a convenience, `operator.add` does the\nsame thing, but beware -- you can't use `operator.and` and a few\nothers where the ``natural'' name for an operator is a reserved\nkeyword. You can add a single trailing underscore in such cases.New built-in module `errno`. See the Library Reference Manual.Rewritten `cgi` module. See the Library Reference Manual.Improved restricted execution module (`rexec`). New module\n`Bastion`. Both are now documented in a new chapter on\nrestricted execution in the Library Reference Manual.New string operations (all described in the Library Reference Manual):\n`lstrip()`, `rstrip()` (strip only the left/right\nwhitespace), `capitalize()` (uppercase the first character,\nlowercase the rest), `capwords()` (capitalize each word,\ndelimited a la `string.split()`), `translate()` (string\ntransliteration - this existed before but can now also delete\ncharacters by specifying a third argument), `maketrans()` (a\nconvenience function for creating translation tables for\n`translate()` and `regex.compile()`). The string function\n`split()` has an optional third argument which specifies the\nmaximum number of separators to split;\ne.g. `string.split('a=b=c', '=', 1)` yields `['a', 'b=c']`.\n(Note that for a long time, `split()` and `splitfields()`\nare synonyms.New regsub operations (see the Library Reference Manual):\n`regsub.capwords()` (like `string.capwords()` but allows you to\nspecify the word delimiter as a regular expression),\n`regsub.splitx()` (like `regsub.split()` but returns the\ndelimiters as well as the words in the resulting list). The optional\n`maxsep` argument is also supported by `regsub.split()`.Module files `pdb.py` and `profile.py` can now be invoked as\nscripts to debug c.q. profile other scripts easily. For example:\n`python /usr/local/lib/python1.4/profile.py myscript.py`The `os` module now supports the `putenv()` function on\nsystems where it is provided in the C library (Windows NT and most\nUnix versions). For example, `os.putenv('PATH',\n'/bin:/usr/bin')` sets the environment variable `PATH` to the\nstring `'/bin:/usr/bin'`. Such changes to the environment affect\nsubprocesses started with `os.system()`, `os.popen()` or\n`os.fork()` and `os.execv()`. When `putenv()` is\nsupported, assignments to items in `os.environ` are automatically\ntranslated into corresponding calls to `os.putenv()`; however,\ncalls to `os.putenv()` don't update `os.environ`, so it is\nactually preferable to assign to items of `os.environ`. For this\npurpose, the type of `os.environ` is changed to a subclass of\n`UserDict.UserDict` when `os.putenv()` is supported.\n(Buglet: `os.execve()` still requires a real dictionary, so it\nwon't accept `os.environ` as its third argument. However, you\ncan now use `os.execv()` and it will use your changes to\n`os.environ`!.)More new functions in the `os` module: `mkfifo`,\n`plock`, `remove` (== `unlink`), and `ftruncate`.\nSee the Unix manual (section 2, system calls) for these function.\nMore functions are also available under NT.New functions in the fcntl module: `lockf()` and `flock()`\n(don't ask `:-)`). See the Library Reference Manual.The first item of the module search path, `sys.path[0]`, is the\ndirectory containing the script that was used to invoke the Python\ninterpreter. If the script directory is not available (e.g. if the\ninterpreter is invoked interactively or if the script is read from\nstandard input), `sys.path[0]` is the empty string, which directs\nPython to search modules in the current directory first. Notice that\nthe script directory is inserted before the entries inserted as\na result of `$PYTHONPATH`. There is no longer an entry for the\ncurrent directory later in the path (unless explicitly set in\n`$PYTHONPATH` or overridden at build time).\n---\nnode115.html node111.html node113.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 4111, "url": "https://docs.python.org/{python_version}/tut/node114.html"} {"title": "13.4 Configuration and Installation", "text": "node116.html node111.html node114.html node1.html\n---\n# 13.4 Configuration and Installation\n- More configuration information is now available to Python programs.\nThe variable `sys.prefix` gives the site-specific directory\nprefix where the platform independent Python files are installed; by\ndefault, this is the string `\"/usr/local\"`. This can be set at\nbuild time with the `-prefix` argument to the `configure`\nscript. The main collection of Python library modules is installed in\nthe directory `sys.prefix+\"/lib/python1.4\"` while the platform\nindependent header files (all except `config.h`) are stored in\n`sys.prefix+\"/include/python1.4\"`.\nSimilarly, the variable `sys.exec_prefix` gives the site-specific\ndirectory prefix where the platform dependent Python files are\ninstalled; by default, this is also `\"/usr/local\"`. This can be\nset at build time with the `-exec-prefix` argument to the\n`configure` script. Specifically, all configuration files\n(e.g. the `config.h` header file) are installed in the directory\n`sys.exec_prefix+\"/lib/python1.4/config\"`, and shared library\nmodules are installed in\n`sys.exec_prefix+\"/lib/python1.4/sharedmodules\"`.\nInclude files are at `sys.prefix+\"/include/python1.4\"`.\nIt is not yet decided what the most portable way is to come up with\nthe version number used in these pathnames. For compatibility with\nthe 1.4beta releases, sys.version[:3] can be used.\nOn non-Unix systems, these variables are meaningless.While sites are strongly discouraged from modifying the standard\nPython library (like adding site-specific modules or functions), there\nis now a standard way to invoke site-specific features. The standard\nmodule `site`, when imported, appends two site-specific\ndirectories to the end of `sys.path`:\n`$prefix/lib/site-python` and\n`$exec_prefix/lib/site-python`, where `$prefix` and\n`$exec_prefix` are the directories `sys.prefix` and\n`sys.exec_prefix` mentioned above.\nAfter this path manipulation has been performed, an attempt is made to\nimport the module `sitecustomize`. Any `ImportError`\nexception raised by this attempt is silently ignored.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2122, "url": "https://docs.python.org/{python_version}/tut/node115.html"} {"title": "About this document ...", "text": "tut.html node115.html node1.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@cnri.reston.va.us tut.tex.\nThe translation was initiated by Fred L. Drake on Fri Dec 6 13:26:41 EST 1996\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 569, "url": "https://docs.python.org/{python_version}/tut/node116.html"} {"title": "2.2.2 The Module Search Path", "text": "node13.html node10.html node11.html node1.html\n---\n## 2.2.2 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@cnri.reston.va.us", "python_version": "1.4", "length": 960, "url": "https://docs.python.org/{python_version}/tut/node12.html"} {"title": "2.2.3 ``Compiled'' Python files", "text": "node14.html node10.html node12.html node1.html\n---\n## 2.2.3 ``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. The\nmodification time of the version of spam.py used to create\nspam.pyc is recorded in spam.pyc, and the file is ignored if\nthese 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 .pyc files for all modules.)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1081, "url": "https://docs.python.org/{python_version}/tut/node13.html"} {"title": "2.2.4 Executable Python scripts", "text": "node15.html node10.html node13.html node1.html\n---\n## 2.2.4 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/local/bin/python\n```\n(assuming that's the name of the interpreter) at the beginning of the\nscript and giving the file an executable mode. The #! must be\nthe first two characters of the file.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 433, "url": "https://docs.python.org/{python_version}/tut/node14.html"} {"title": "2.2.5 The Interactive Startup File", "text": "node16.html node10.html node14.html node1.html\n---\n## 2.2.5 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, e.g.\n`import os;` `execfile(os.environ['PYTHONSTARTUP'])`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1216, "url": "https://docs.python.org/{python_version}/tut/node15.html"} {"title": "2.3 Interactive Input Editing and History Substitution", "text": "node17.html node6.html node15.html node1.html\n---\n# 2.3 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.\nPerhaps the quickest check to see whether command line editing is\nsupported is typing Control-P to the first Python prompt you get. If\nit beeps, you have command line editing. If nothing appears to\nhappen, or if `^P` is echoed, you can skip the rest of this\nsection.\n---\n- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)\n2.3.2 History Substitution (node18.html#SECTION00332000000000000000)\n2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)\n2.3.4 Commentary (node20.html#SECTION00334000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1047, "url": "https://docs.python.org/{python_version}/tut/node16.html"} {"title": "2.3.1 Line Editing", "text": "node18.html node16.html node16.html node1.html\n---\n## 2.3.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@cnri.reston.va.us", "python_version": "1.4", "length": 740, "url": "https://docs.python.org/{python_version}/tut/node17.html"} {"title": "2.3.2 History Substitution", "text": "node19.html node16.html node17.html node1.html\n---\n## 2.3.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@cnri.reston.va.us", "python_version": "1.4", "length": 633, "url": "https://docs.python.org/{python_version}/tut/node18.html"} {"title": "2.3.3 Key Bindings", "text": "node20.html node16.html node18.html node1.html\n---\n## 2.3.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@cnri.reston.va.us", "python_version": "1.4", "length": 950, "url": "https://docs.python.org/{python_version}/tut/node19.html"} {"title": "1 Whetting Your Appetite", "text": "node3.html tut.html node1.html node1.html\n---\n# 1 Whetting Your Appetite\n---\n- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)\n1.2 Introduction (node4.html#SECTION00220000000000000000)\n1.3 Where From Here (node5.html#SECTION00230000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 281, "url": "https://docs.python.org/{python_version}/tut/node2.html"} {"title": "2.3.4 Commentary", "text": "node21.html node16.html node19.html node1.html\n---\n## 2.3.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@cnri.reston.va.us", "python_version": "1.4", "length": 517, "url": "https://docs.python.org/{python_version}/tut/node20.html"} {"title": "3 An Informal Introduction to Python", "text": "node22.html tut.html node20.html node1.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.footnode.html#116\nNote 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 (node22.html#SECTION00410000000000000000)\n- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)\n3.1.2 Strings (node24.html#SECTION00412000000000000000)\n3.1.3 Lists (node25.html#SECTION00413000000000000000)\n3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 874, "url": "https://docs.python.org/{python_version}/tut/node21.html"} {"title": "3.1 Using Python as a Calculator", "text": "node23.html node21.html node21.html node1.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- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)\n3.1.2 Strings (node24.html#SECTION00412000000000000000)\n3.1.3 Lists (node25.html#SECTION00413000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 410, "url": "https://docs.python.org/{python_version}/tut/node22.html"} {"title": "3.1.1 Numbers", "text": "node24.html node22.html node22.html node1.html\n---\n## 3.1.1 Numbers\nThe interpreter acts as a simple calculator: you can type an\nexpression at it and it will write the value. Expression syntax is\nstraightforward: the operators +, -, * and /\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>>>\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>>>\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>>>\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>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1080, "url": "https://docs.python.org/{python_version}/tut/node23.html"} {"title": "3.1.2 Strings", "text": "node25.html node22.html node23.html node1.html\n---\n## 3.1.2 Strings\nBesides numbers, Python can also manipulate strings, enclosed in\nsingle quotes or double 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>>>\n```\nStrings are written the same way as they are typed for input: inside\nquotes and with quotes and other funny characters escaped by backslashes,\nto show the precise value. The string is enclosed in double quotes if\nthe string contains a single quote and no double quotes, else it's\nenclosed in single quotes. (The print statement, described later,\ncan be used to 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>>>\n```\nStrings can be subscripted (indexed); like in C, the first character of\na string has subscript (index) 0.\nThere is no separate character type; a character is simply a string of\nsize one. Like in Icon, substrings can be specified with the\nslice notation: two indices separated by a colon.\n```text\n>>> word[4]\n'A'\n>>> word[0:2]\n'He'\n>>> word[2:4]\n'lp'\n>>>\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>>>\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>>>\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>>>\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>>>\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>>>\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>>>\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\n`word[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```\n---\nnode25.html node22.html node23.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3643, "url": "https://docs.python.org/{python_version}/tut/node24.html"} {"title": "3.1.3 Lists", "text": "node26.html node22.html node24.html node1.html\n---\n## 3.1.3 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>>>\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>>>\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>>>\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>>>\n```\nThe built-in function len() also applies to lists:\n```text\n>>> len(a)\n8\n>>>\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>>>\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@cnri.reston.va.us", "python_version": "1.4", "length": 1863, "url": "https://docs.python.org/{python_version}/tut/node25.html"} {"title": "3.2 First Steps Towards Programming", "text": "node27.html node21.html node25.html node1.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>>>\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: b <\n10) remains true. In Python, like in C, any non-zero integer value is\ntrue; zero is false. The condition may also be a string or list value,\nin fact any sequence; anything with a non-zero length is true, empty\nsequences are false. The test used in the example is a simple\ncomparison. The standard comparison operators are written the same as\nin C: <, >, ==, <=, >= 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>>>\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>>>\n```\nNote that the interpreter inserts a newline before it prints the next\nprompt if the last line was not completed.\n---\nnode27.html node21.html node25.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2534, "url": "https://docs.python.org/{python_version}/tut/node26.html"} {"title": "4 More Control Flow Tools", "text": "node28.html tut.html node26.html node1.html\n---\n# 4 More Control Flow Tools\nBesides the while statement just introduced, Python knows the\nusual control flow statements known from other languages, with some\ntwists.\n---\n- 4.1 If Statements (node28.html#SECTION00510000000000000000)\n4.2 For Statements (node29.html#SECTION00520000000000000000)\n4.3 The range() Function (node30.html#SECTION00530000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)\n4.5 Pass Statements (node32.html#SECTION00550000000000000000)\n4.6 Defining Functions (node33.html#SECTION00560000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 665, "url": "https://docs.python.org/{python_version}/tut/node27.html"} {"title": "4.1 If Statements", "text": "node29.html node27.html node27.html node1.html\n---\n# 4.1 If Statements\nPerhaps the most well-known statement type is the if statement.\nFor 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 part is\noptional. The keyword `elif' is short for `else if', and is\nuseful to avoid excessive indentation. An if...elif...elif...\nsequence is a substitute for the switch or case statements\nfound in other languages.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 615, "url": "https://docs.python.org/{python_version}/tut/node28.html"} {"title": "4.2 For Statements", "text": "node30.html node27.html node28.html node1.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 list\nor 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>>>\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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1150, "url": "https://docs.python.org/{python_version}/tut/node29.html"} {"title": "1.1 Disclaimer", "text": "node4.html node2.html node2.html node1.html\n---\n# 1.1 Disclaimer\nNow that there are several books out on Python, this tutorial has lost\nits role as the only introduction to Python for most new users. It\ntakes time to keep a document like this up to date in the face of\nadditions to the language, and I simply don't have enough time to do a\ngood job. Therefore, this version of the tutorial is almost unchanged\nsince the previous release. This doesn't mean that the tutorial is\nout of date -- all the examples still work exactly as before. There\nare simply some new areas of the language that aren't covered.\nTo make up for this, there are some chapters at the end cover\nimportant changes in recent Python releases, and these are up to date\nwith the current release.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 793, "url": "https://docs.python.org/{python_version}/tut/node3.html"} {"title": "4.3 The range() Function", "text": "node31.html node27.html node29.html node1.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 containing\narithmetic progressions, e.g.:\n```text\n>>> range(10)\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>>\n```\nThe given end point is never part of the generated list; range(10)\ngenerates a list of 10 values, exactly the legal indices for items of a\nsequence of length 10. It is possible to let the range start at another\nnumber, or to specify a different increment (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>>>\n```\nTo iterate over the indices of a sequence, combine range() and\nlen() 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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 950, "url": "https://docs.python.org/{python_version}/tut/node30.html"} {"title": "4.4 Break and Continue Statements, and Else Clauses on Loops", "text": "node32.html node27.html node30.html node1.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 with the\nnext iteration of the loop.\nLoop statements may have an else clause; it is executed when the\nloop terminates through exhaustion of the list (with for) or when\nthe condition becomes false (with while), but not when the loop is\nterminated by a break statement. This is exemplified by the\nfollowing loop, which 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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 950, "url": "https://docs.python.org/{python_version}/tut/node31.html"} {"title": "4.5 Pass Statements", "text": "node33.html node27.html node31.html node1.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@cnri.reston.va.us", "python_version": "1.4", "length": 313, "url": "https://docs.python.org/{python_version}/tut/node32.html"} {"title": "4.6 Defining Functions", "text": "node34.html node27.html node32.html node1.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... 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>>>\n```\nThe keyword def introduces a function definition. It must\nbe followed by the function name and the parenthesized list of formal\nparameters. The statements that form the body of the function starts at\nthe next line, indented by a tab stop.\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\nvariable references first look in the local symbol table, then\nin the global symbol table, and then in the table of built-in names.\nThus,\nglobal 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#841\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\ncurrent\nsymbol table. The value\nof 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>>>\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>>>\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... 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>>>\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 the middle\nof a procedure (falling off the end also returns from a procedure), in\nwhich 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\nit is equivalent to result = result + [b], but more efficient.\n---\nnode34.html node27.html node32.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3801, "url": "https://docs.python.org/{python_version}/tut/node33.html"} {"title": "5 Odds and Ends", "text": "node35.html tut.html node33.html node1.html\n---\n# 5 Odds and Ends\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 (node35.html#SECTION00610000000000000000)\n5.2 The del statement (node36.html#SECTION00620000000000000000)\n5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)\n5.4 Dictionaries (node38.html#SECTION00640000000000000000)\n5.5 More on Conditions (node39.html#SECTION00650000000000000000)\n5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 610, "url": "https://docs.python.org/{python_version}/tut/node34.html"} {"title": "5.1 More on Lists", "text": "node36.html node34.html node34.html node1.html\n---\n# 5.1 More on Lists\nThe list data type has some more methods. Here are all of the methods\nof lists 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---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 596, "url": "https://docs.python.org/{python_version}/tut/node35.html"} {"title": "5.2 The del statement", "text": "node37.html node34.html node35.html node1.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>>>\n```\ndel can also be used to delete entire variables:\n```text\n>>> del a\n>>>\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@cnri.reston.va.us", "python_version": "1.4", "length": 683, "url": "https://docs.python.org/{python_version}/tut/node36.html"} {"title": "5.3 Tuples and Sequences", "text": "node38.html node34.html node36.html node1.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, other\nsequence data types may be added. There is also another standard\nsequence 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>>>\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>>>\n```\nThe statement t = 12345, 54321, 'hello!' is an example of\ntuple packing: the values 12345, 54321 and 'hello!'\nare packed together in a tuple. The reverse operation is also\npossible, e.g.:\n```text\n>>> x, y, z = t\n>>>\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```\n---\nnode38.html node34.html node36.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2481, "url": "https://docs.python.org/{python_version}/tut/node37.html"} {"title": "5.4 Dictionaries", "text": "node39.html node34.html node37.html node1.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 are strings (the use of non-string values as keys\nis supported, but beyond the scope of this tutorial).\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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1811, "url": "https://docs.python.org/{python_version}/tut/node38.html"} {"title": "5.5 More on Conditions", "text": "node40.html node34.html node38.html node1.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 right,\nand evaluation stops as soon as the outcome is determined. E.g., if\nA and C are true but B is false, A and B and C\ndoes not evaluate the expression C. In general, the return value of a\nshortcut operator, when used as a general value and not as a Boolean, is\nthe 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>>>\n```\nNote that in Python, unlike C, assignment cannot occur inside expressions.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1801, "url": "https://docs.python.org/{python_version}/tut/node39.html"} {"title": "1.2 Introduction", "text": "node5.html node2.html node3.html node1.html\n---\n# 1.2 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 because the problem requires variable-length\nstrings or other data types (like sorted lists of file names) that are\neasy in the shell but lots of work to implement in C; or perhaps just\nbecause you're not sufficiently familiar with C.\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 in\nPython 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 a generic interface to window systems (STDWIN).\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\nfunction or\nmodule 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\nPython's Flying Circus'' and has nothing to do with nasty reptiles...\n---\nnode5.html node2.html node3.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3121, "url": "https://docs.python.org/{python_version}/tut/node4.html"} {"title": "5.6 Comparing Sequences and Other Types", "text": "node41.html node34.html node39.html node1.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#283\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1460, "url": "https://docs.python.org/{python_version}/tut/node40.html"} {"title": "6 Modules", "text": "node42.html tut.html node40.html node1.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>>>\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>>>\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---\n- 6.1 More on Modules (node42.html#SECTION00710000000000000000)\n6.2 Standard Modules (node43.html#SECTION00720000000000000000)\n6.3 The dir() function (node44.html#SECTION00730000000000000000)\n---\nnode42.html tut.html node40.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2542, "url": "https://docs.python.org/{python_version}/tut/node41.html"} {"title": "6.1 More on Modules", "text": "node43.html node41.html node41.html node1.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#296\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>>>\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>>>\n```\nThis imports all names except those beginning with an underscore\n(_).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1604, "url": "https://docs.python.org/{python_version}/tut/node42.html"} {"title": "6.2 Standard Modules", "text": "node44.html node41.html node42.html node1.html\n---\n# 6.2 Standard Modules\nPython comes with a library of standard modules, described in a separate\ndocument (Python Library Reference). Some modules are built into the\ninterpreter; these provide access to operations that are not part of the\ncore of the language but are nevertheless built in, either for\nefficiency or to provide access to operating system primitives such as\nsystem calls. The set of such modules is a configuration option; e.g.,\nthe amoeba module is only provided on systems that somehow support\nAmoeba primitives. One particular module deserves some attention:\nsys, which is built into every Python interpreter. The variables\nsys.ps1 and sys.ps2 define the strings used as primary and\nsecondary 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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1358, "url": "https://docs.python.org/{python_version}/tut/node43.html"} {"title": "6.3 The dir() function", "text": "node45.html node41.html node43.html node1.html\n---\n# 6.3 The dir() function\nThe built-in function dir is used to find out which names a module\ndefines. 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>>>\n```\nWithout arguments, dir() lists the names you have defined currently:\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>>>\n```\nNote that it lists all types of names: variables, modules, functions, etc.\ndir() does not list the names of built-in functions and variables.\nIf you want a list of those, they are defined in the standard module\n__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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1601, "url": "https://docs.python.org/{python_version}/tut/node44.html"} {"title": "7 Output Formatting", "text": "node46.html tut.html node44.html node1.html\n---\n# 7 Output Formatting\nSo far we've encountered two ways of writing values: expression\nstatements and the print statement. (A third way is using the\nwrite method of file objects; the standard output file can be\nreferenced as sys.stdout. See the Library Reference for more\ninformation on this.)\nOften you'll want more control over the formatting of your output than\nsimply printing space-separated values. The key to nice formatting in\nPython is to do all the string handling yourself; using string slicing\nand concatenation operations you can create any lay-out you can imagine.\nThe standard module string contains some useful operations for\npadding strings to a given column width; these will be discussed shortly.\nFinally, the `%` operator (modulo) with a string left argument\ninterprets this string as a C sprintf format string to be applied to the\nright argument, and returns the string resulting from this formatting\noperation.\nOne question remains, of course: how do you convert values to strings?\nLuckily, Python has a way to convert any value to a string: just write\nthe value between reverse 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 = `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>>>\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```\n(Note that one space between each column was added by the way print\nworks: it always adds spaces between its arguments.)\nThis example demonstrates the function string.rjust(), which\nright-justifies a string in a field of a given width by padding it with\nspaces on the left. There are similar functions string.ljust()\nand string.center(). These functions do not write anything, they\njust return a new string. If the input string is too long, they don't\ntruncate it, but return it unchanged; this will mess up your column\nlay-out but that's usually better than the alternative, which would be\nlying about a value. (If you really want truncation you can always add\na slice operation, as in string.ljust(x, n)[0:n].)\nThere is another function, string.zfill, which pads a numeric\nstring on the left with zeros. It understands about plus and minus\nsigns:\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>>>\n```\n---\nnode46.html tut.html node44.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 3278, "url": "https://docs.python.org/{python_version}/tut/node45.html"} {"title": "8 Errors and Exceptions", "text": "node47.html tut.html node45.html node1.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 (node47.html#SECTION00910000000000000000)\n8.2 Exceptions (node48.html#SECTION00920000000000000000)\n8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)\n8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)\n8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)\n8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 712, "url": "https://docs.python.org/{python_version}/tut/node46.html"} {"title": "8.1 Syntax Errors", "text": "node48.html node46.html node46.html node1.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>>>\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@cnri.reston.va.us", "python_version": "1.4", "length": 786, "url": "https://docs.python.org/{python_version}/tut/node47.html"} {"title": "8.2 Exceptions", "text": "node49.html node46.html node47.html node1.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>>>\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 Python Library Reference Manual lists the built-in exceptions and\ntheir meanings.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1785, "url": "https://docs.python.org/{python_version}/tut/node48.html"} {"title": "8.3 Handling Exceptions", "text": "node50.html node46.html node48.html node1.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>>>\n```\nThe try statement works as follows.\n- First, the\ntry clause\n(the statement(s) between the try and except keywords) is\nexecuted.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\nits type matches the exception named after the except keyword,\nthe rest of the try clause is skipped, the except clause is executed,\nand then execution 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 no handler is\nfound, it is an\nunhandled exception\nand execution stops with a message as shown above.\nA try statement may have more than one except clause, to specify\nhandlers 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!\nWhen an exception occurs, it may have an associated value, also known as\nthe exceptions's\nargument.\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>>>\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```\n---\nnode50.html node46.html node48.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2867, "url": "https://docs.python.org/{python_version}/tut/node49.html"} {"title": "1.3 Where From Here", "text": "node6.html node2.html node4.html node1.html\n---\n# 1.3 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.\nWhen you're through with the tutorial (or just getting bored), you\nshould read the Library Reference, which gives complete (though terse)\nreference material about built-in and standard types, functions and\nmodules that can save you a lot of time when writing Python programs.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 995, "url": "https://docs.python.org/{python_version}/tut/node5.html"} {"title": "8.4 Raising Exceptions", "text": "node51.html node46.html node49.html node1.html\n---\n# 8.4 Raising Exceptions\nThe raise statement allows the programmer to force a specified\nexception to occur.\nFor example:\n```text\n>>> raise NameError, 'HiThere'\nTraceback (innermost last):\nFile \"\", line 1\nNameError: HiThere\n>>>\n```\nThe first argument to raise names the exception to be raised.\nThe optional second argument specifies the exception's argument.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 443, "url": "https://docs.python.org/{python_version}/tut/node50.html"} {"title": "8.5 User-defined Exceptions", "text": "node52.html node46.html node50.html node1.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>>>\n```\nMany standard modules use this to report errors that may occur in\nfunctions they define.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 543, "url": "https://docs.python.org/{python_version}/tut/node51.html"} {"title": "8.6 Defining Clean-up Actions", "text": "node53.html node46.html node51.html node1.html\n---\n# 8.6 Defining Clean-up Actions\nThe try statement has another optional clause which is intended to\ndefine clean-up actions that must be executed under all circumstances.\nFor 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>>>\n```\nA finally clause is executed whether or not an exception has\noccurred in the try clause. When an exception has occurred, it\nis re-raised after the finally clause is executed. The\nfinally clause is also executed ``on the way out'' when the\ntry statement is left via a break or return\nstatement.\nA try statement must either have one or more except\nclauses or one finally clause, but not both.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 835, "url": "https://docs.python.org/{python_version}/tut/node52.html"} {"title": "9 Classes", "text": "node54.html tut.html node52.html node1.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 (node54.html#SECTION001010000000000000000)\n9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)\n9.3 A first look at classes (node56.html#SECTION001030000000000000000)\n- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)\n9.3.2 Class objects (node58.html#SECTION001032000000000000000)\n9.3.3 Instance objects (node59.html#SECTION001033000000000000000)\n9.3.4 Method objects (node60.html#SECTION001034000000000000000)\n9.4 Random remarks (node61.html#SECTION001040000000000000000)\n9.5 Inheritance (node62.html#SECTION001050000000000000000)\n- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)\n9.6 Odds and ends (node64.html#SECTION001060000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2356, "url": "https://docs.python.org/{python_version}/tut/node53.html"} {"title": "9.1 A word about terminology", "text": "node55.html node53.html node53.html node1.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 unlike\nSmalltalk, not all types in Python are classes: the basic built-in\ntypes like integers and lists aren't, and even somewhat more exotic\ntypes like files aren't. However, all Python types share a little\nbit of common semantics that is best described by using the word\nobject.\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@cnri.reston.va.us", "python_version": "1.4", "length": 1741, "url": "https://docs.python.org/{python_version}/tut/node54.html"} {"title": "9.2 Python scopes and name spaces", "text": "node56.html node53.html node54.html node1.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\n`modname.funcname`, `modname` is a module object and\n`funcname` is an attribute of it. In this case there happens to\nbe a straightforward mapping between the module's attributes and the\nglobal names defined in the module: they share the same name space!footnode.html#844\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 `__main__`,\nso they have their own global name space. (The built-in names\nactually also live in a module; this is called `__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\n`global` statement can be used to indicate that particular\nvariables live in the global scope.)\n---\nnode56.html node53.html node54.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 5006, "url": "https://docs.python.org/{python_version}/tut/node55.html"} {"title": "9.3 A first look at classes", "text": "node57.html node53.html node55.html node1.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- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)\n9.3.2 Class objects (node58.html#SECTION001032000000000000000)\n9.3.3 Instance objects (node59.html#SECTION001033000000000000000)\n9.3.4 Method objects (node60.html#SECTION001034000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 474, "url": "https://docs.python.org/{python_version}/tut/node56.html"} {"title": "9.3.1 Class definition syntax", "text": "node58.html node56.html node56.html node1.html\n---\n## 9.3.1 Class definition syntax\nThe simplest form of class definition looks like this:\n```text\nclass ClassName:\n\n.\n.\n.\n\n```\nClass definitions, like function definitions (`def` statements)\nmust be executed before they have any effect. (You could conceivably\nplace a class definition in a branch of an `if` statement, or\ninside 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@cnri.reston.va.us", "python_version": "1.4", "length": 1498, "url": "https://docs.python.org/{python_version}/tut/node57.html"} {"title": "9.3.2 Class objects", "text": "node59.html node56.html node57.html node1.html\n---\n## 9.3.2 Class objects\nClass objects support two kinds of operations: attribute references\nand instantiation.\nAttribute references use the standard syntax used for all\nattribute references in Python: `obj.name`. Valid attribute\nnames are all the names that were in the class's name space when the\nclass object was created. So, if the class definition looked like\nthis:\n```text\nclass MyClass:\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\nvalue of `MyClass.i` by assignment.\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@cnri.reston.va.us", "python_version": "1.4", "length": 1041, "url": "https://docs.python.org/{python_version}/tut/node58.html"} {"title": "9.3.3 Instance objects", "text": "node60.html node56.html node58.html node1.html\n---\n## 9.3.3 Instance objects\nNow what can we do with instance objects? The only operations\nunderstood by instance objects are attribute references. There are\ntwo kinds of valid attribute names.\nThe first I'll call data attributes. These correspond to\n``instance variables'' in Smalltalk, and to ``data members'' in C++.\nData attributes need not be declared; like local variables, they\nspring into existence when they are first assigned to. For example,\nif `x` in the instance of `MyClass` created above, the\nfollowing piece of code will print the value 16, without leaving a\ntrace:\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\n`MyClass.f` is a function, but `x.i` is not, since\n`MyClass.i` is not. But `x.f` is not the\nsame thing as `MyClass.f` -- it is a method object, not a\nfunction object.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1638, "url": "https://docs.python.org/{python_version}/tut/node59.html"} {"title": "2 Using the Python Interpreter", "text": "node7.html tut.html node5.html node1.html\n---\n# 2 Using the Python Interpreter\n---\n- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)\n- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)\n2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)\n2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)\n- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)\n2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)\n2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)\n2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)\n2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)\n2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)\n- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)\n2.3.2 History Substitution (node18.html#SECTION00332000000000000000)\n2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)\n2.3.4 Commentary (node20.html#SECTION00334000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1104, "url": "https://docs.python.org/{python_version}/tut/node6.html"} {"title": "9.3.4 Method objects", "text": "node61.html node56.html node59.html node1.html\n---\n## 9.3.4 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---\nnode61.html node56.html node59.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1979, "url": "https://docs.python.org/{python_version}/tut/node60.html"} {"title": "9.4 Random remarks", "text": "node62.html node53.html node60.html node1.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\n`self`. This is nothing more than a convention: the name\n`self` has absolutely no special meaning to Python. (Note,\nhowever, that by not following the convention your code may be less\nreadable by other Python programmers, and it is also conceivable that\na class browser program be written which relies upon such a\nconvention.)\nAny function object that is a class attribute defines a method for\ninstances of that class. It is not necessary that the function\ndefinition is textually enclosed in the class definition: assigning a\nfunction object to a local variable in the class is also ok. For\nexample:\n```text\n# 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\n`C` that refer to function objects, and consequently they are all\nmethods of instances of `C` -- `h` being exactly equivalent\nto `g`. Note that this practice usually only serves to confuse\nthe reader of a program.\nMethods may call other methods by using method attributes of the\n`self` argument, e.g.:\n```text\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 instantiation\nautomatically invokes `__init__` for the newly-created class\ninstance. So in the `Bag` example, a new and initialized instance\ncan be obtained by:\n```text\nx = Bag()\n```\nOf course, the `__init__` method may have arguments for greater\nflexibility. In that case, arguments given to the class instantiation\noperator are passed on to `__init__`. For example,\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>>>\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---\nnode62.html node53.html node60.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 4552, "url": "https://docs.python.org/{python_version}/tut/node61.html"} {"title": "9.5 Inheritance", "text": "node63.html node53.html node61.html node1.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:\n`DerivedClassName()` creates a new instance of the class. Method\nreferences are resolved as follows: the corresponding class attribute\nis searched, descending down the chain of base classes if necessary,\nand the method reference is valid if this yields a function object.\nDerived classes may override methods of their base classes. Because\nmethods have no special privileges when calling other methods of the\nsame object, a method of a base class that calls another method\ndefined in the same base class, may in fact end up calling a method of\na derived class that overrides it. (For C++ programmers: all methods\nin Python are ``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- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)\n---\nnode63.html node53.html node61.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2239, "url": "https://docs.python.org/{python_version}/tut/node62.html"} {"title": "9.5.1 Multiple inheritance", "text": "node64.html node62.html node62.html node1.html\n---\n## 9.5.1 Multiple inheritance\nPython supports a limited form of multiple inheritance as well. A\nclass definition with multiple base classes looks as follows:\n```text\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\n`DerivedClassName`, 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\n`Base3` 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\n`Base1`.)\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@cnri.reston.va.us", "python_version": "1.4", "length": 1659, "url": "https://docs.python.org/{python_version}/tut/node63.html"} {"title": "9.6 Odds and ends", "text": "node65.html node53.html node63.html node1.html\n---\n# 9.6 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\n`read()` 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\n`sys.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---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1309, "url": "https://docs.python.org/{python_version}/tut/node64.html"} {"title": "10 Recent Additions as of Release 1.1", "text": "node66.html tut.html node64.html node1.html\n---\n# 10 Recent Additions as of Release 1.1\nPython is an evolving language. Since this tutorial was last\nthoroughly revised, several new features have been added to the\nlanguage. While ideally I should revise the tutorial to incorporate\nthem in the mainline of the text, lack of time currently requires me\nto take a more modest approach. In this chapter I will briefly list the\nmost important improvements to the language and how you can use them\nto your benefit.\n---\n- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)\n10.2 String Literals (node67.html#SECTION001120000000000000000)\n- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)\n10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)\n10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)\n10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)\n10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)\n- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)\n10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)\n10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)\n- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)\n10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)\n10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)\n- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)\n10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)\n- Map. (node81.html#SECTION001152100000000000000)\nFilter. (node82.html#SECTION001152200000000000000)\nReduce. (node83.html#SECTION001152300000000000000)\n10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)\n10.7 Regular Expressions (node85.html#SECTION001170000000000000000)\n10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)\n10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)\n10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)\n10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)\n- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)\n10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)\n10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2512, "url": "https://docs.python.org/{python_version}/tut/node65.html"} {"title": "10.1 The Last Printed Expression", "text": "node67.html node65.html node65.html node1.html\n---\n# 10.1 The Last Printed Expression\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>>>\n```\nFor reasons too embarrassing to explain, this variable is implemented\nas a built-in (living in the module `__builtin__`), so it should\nbe treated as read-only by the user. I.e. don't explicitly assign a\nvalue to it -- you would create an independent local variable with\nthe same name masking the built-in variable with its magic behavior.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 778, "url": "https://docs.python.org/{python_version}/tut/node66.html"} {"title": "10.2 String Literals", "text": "node68.html node65.html node66.html node1.html\n---\n# 10.2 String Literals\n---\n- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)\n10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)\n10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)\n10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 404, "url": "https://docs.python.org/{python_version}/tut/node67.html"} {"title": "10.2.1 Double Quotes", "text": "node69.html node67.html node67.html node1.html\n---\n## 10.2.1 Double Quotes\nPython can now also use double quotes to surround string literals,\ne.g. `\"this doesn't hurt a bit\"`. There is no semantic\ndifference between strings surrounded by single or double quotes.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 290, "url": "https://docs.python.org/{python_version}/tut/node68.html"} {"title": "10.2.2 Continuation Of String Literals", "text": "node70.html node67.html node68.html node1.html\n---\n## 10.2.2 Continuation Of String Literals\nString literals can span multiple lines by escaping newlines with\nbackslashes, 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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 602, "url": "https://docs.python.org/{python_version}/tut/node69.html"} {"title": "2.1 Invoking the Interpreter", "text": "node8.html node6.html node6.html node1.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.)\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 >> import math\n>>> print 'The value of PI is approximately %5.3f.' % math.pi\nThe value of PI is approximately 3.142.\n>>>\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>>>\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 `str()`\nbuilt-in function. Using `*` to pass the width or precision in\nas a separate (integer) argument is supported. The C formats\n`%n` and `%p` are not supported.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1178, "url": "https://docs.python.org/{python_version}/tut/node73.html"} {"title": "10.3.2 Referencing Variables By Name", "text": "node75.html node72.html node73.html node1.html\n---\n## 10.3.2 Referencing Variables By Name\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>>>\n```\nThis is particularly useful in combination with the new built-in\n`vars()` function, which returns a dictionary containing all\nlocal variables.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 712, "url": "https://docs.python.org/{python_version}/tut/node74.html"} {"title": "10.4 Optional Function Arguments", "text": "node76.html node65.html node74.html node1.html\n---\n# 10.4 Optional Function Arguments\nIt is now possible to define functions with a variable number of\narguments. There are two forms, which can be combined.\n---\n- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)\n10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 388, "url": "https://docs.python.org/{python_version}/tut/node75.html"} {"title": "10.4.1 Default Argument Values", "text": "node77.html node75.html node75.html node1.html\n---\n## 10.4.1 Default Argument Values\nThe most useful form is to specify a default value for one or more\narguments. This creates a function that can be called with fewer\narguments than it is defined, e.g.\n```text\ndef ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'):\nwhile 1:\nok = raw_input(prompt)\nif ok in ('y', 'ye', 'yes'): return 1\nif ok in ('n', 'no', 'nop', 'nope'): return 0\nretries = retries - 1\nif retries < 0: raise IOError, 'refusenik user'\nprint complaint\n```\nThis function can be called either like this:\n`ask_ok('Do you really want to quit?')` or like this:\n`ask_ok('OK to overwrite the file?', 2)`.\nThe default values are evaluated at the point of function definition\nin the defining scope, so that e.g.\n```text\ni = 5\ndef f(arg = i): print arg\ni = 6\nf()\n```\nwill print `5`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 877, "url": "https://docs.python.org/{python_version}/tut/node76.html"} {"title": "10.4.2 Arbitrary Argument Lists", "text": "node78.html node75.html node76.html node1.html\n---\n## 10.4.2 Arbitrary Argument Lists\nIt is also possible to specify that a function can be called with an\narbitrary number of arguments. These arguments will be wrapped up in\na tuple. Before the variable number of arguments, zero or more normal\narguments may occur, e.g.\n```text\ndef fprintf(file, format, *args):\nfile.write(format % args)\n```\nThis feature may be combined with the previous, e.g.\n```text\ndef but_is_it_useful(required, optional = None, *remains):\nprint \"I don't know\"\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 564, "url": "https://docs.python.org/{python_version}/tut/node77.html"} {"title": "10.5 Lambda And Functional Programming Tools", "text": "node79.html node65.html node77.html node1.html\n---\n# 10.5 Lambda And Functional Programming Tools\n---\n- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)\n10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)\n- Map. (node81.html#SECTION001152100000000000000)\nFilter. (node82.html#SECTION001152200000000000000)\nReduce. (node83.html#SECTION001152300000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 419, "url": "https://docs.python.org/{python_version}/tut/node78.html"} {"title": "10.5.1 Lambda Forms", "text": "node80.html node78.html node78.html node1.html\n---\n## 10.5.1 Lambda Forms\nBy popular demand, a few features commonly found in functional\nprogramming languages and Lisp have been added to Python. With the\n`lambda` 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@cnri.reston.va.us", "python_version": "1.4", "length": 827, "url": "https://docs.python.org/{python_version}/tut/node79.html"} {"title": "2.1.1 Argument Passing", "text": "node9.html node7.html node7.html node1.html\n---\n## 2.1.1 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 one;\nwhen no script and no arguments are given, sys.argv[0] is an\nempty 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@cnri.reston.va.us", "python_version": "1.4", "length": 651, "url": "https://docs.python.org/{python_version}/tut/node8.html"} {"title": "10.5.2 Map, Reduce and Filter", "text": "node81.html node78.html node79.html node1.html\n---\n## 10.5.2 Map, Reduce and Filter\nThree new built-in functions on sequences are good candidate to pass\nlambda forms.\n---\n- Map. (node81.html#SECTION001152100000000000000)\nFilter. (node82.html#SECTION001152200000000000000)\nReduce. (node83.html#SECTION001152300000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 350, "url": "https://docs.python.org/{python_version}/tut/node80.html"} {"title": "Map.", "text": "node82.html node80.html node80.html node1.html\n---\n### Map.\n`map(function, sequence)` calls `function(item)` for each of\nthe sequence's items and returns a list of the return values. For\nexample, to compute some cubes:\n```text\n>>> map(lambda x: x*x*x, range(1, 11))\n[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]\n>>>\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 turning a pair\nof lists into a list of pairs. For example:\n```text\n>>> seq = range(8)\n>>> map(None, seq, map(lambda x: x*x, seq))\n[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 963, "url": "https://docs.python.org/{python_version}/tut/node81.html"} {"title": "Filter.", "text": "node83.html node80.html node81.html node1.html\n---\n### Filter.\n`filter(function, sequence)` returns a sequence (of the same\ntype, if possible) consisting of those items from the sequence for\nwhich `function(item)` is true. For example, to compute some\nprimes:\n```text\n>>> filter(lambda x: x%2 != 0 and x%3 != 0, range(2, 25))\n[5, 7, 11, 13, 17, 19, 23]\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 388, "url": "https://docs.python.org/{python_version}/tut/node82.html"} {"title": "Reduce.", "text": "node84.html node80.html node82.html node1.html\n---\n### Reduce.\n`reduce(function, sequence)` returns a single value constructed\nby calling the (binary) function on the first two items of the\nsequence, then on the result and the next item, and so on. For\nexample, to compute the sum of the numbers 1 through 10:\n```text\n>>> reduce(lambda x, y: x+y, range(1, 11))\n55\n>>>\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... return reduce(lambda x, y: x+y, seq, 0)\n...\n>>> sum(range(1, 11))\n55\n>>> sum([])\n0\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 912, "url": "https://docs.python.org/{python_version}/tut/node83.html"} {"title": "10.6 Continuation Lines Without Backslashes", "text": "node85.html node65.html node83.html node1.html\n---\n# 10.6 Continuation Lines Without Backslashes\nWhile the general mechanism for continuation of a source line on the\nnext physical line remains to place a backslash on the end of the\nline, expressions inside matched parentheses (or square brackets, or\ncurly braces) can now also be continued without using a backslash.\nThis is particularly useful for calls to functions with many\narguments, and for initializations of large tables.\nFor example:\n```text\nmonth_names = ['Januari', 'Februari', 'Maart',\n'April', 'Mei', 'Juni',\n'Juli', 'Augustus', 'September',\n'Oktober', 'November', 'December']\n```\nand\n```text\nCopyInternalHyperLinks(self.context.hyperlinks,\ncopy.context.hyperlinks,\nuidremap)\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 771, "url": "https://docs.python.org/{python_version}/tut/node84.html"} {"title": "10.7 Regular Expressions", "text": "node86.html node65.html node84.html node1.html\n---\n# 10.7 Regular Expressions\nWhile C's printf-style output formats, transformed into Python, are\nadequate for most output formatting jobs, C's scanf-style input\nformats are not very powerful. Instead of scanf-style input, Python\noffers Emacs-style regular expressions as a powerful input and\nscanning mechanism. Read the corresponding section in the Library\nReference for a full description.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 468, "url": "https://docs.python.org/{python_version}/tut/node85.html"} {"title": "10.8 Generalized Dictionaries", "text": "node87.html node65.html node85.html node1.html\n---\n# 10.8 Generalized Dictionaries\nThe keys of dictionaries are no longer restricted to strings -- they\ncan be any immutable basic type including strings, numbers, tuples, or\n(certain) class instances. (Lists and dictionaries are not acceptable\nas dictionary keys, in order to avoid problems when the object used as\na key is modified.)\nDictionaries have two new methods: `d.values()` returns a list of\nthe dictionary's values, and `d.items()` returns a list of the\ndictionary's (key, value) pairs. Like `d.keys()`, these\noperations are slow for large dictionaries. Examples:\n```text\n>>> d = {100: 'honderd', 1000: 'duizend', 10: 'tien'}\n>>> d.keys()\n[100, 10, 1000]\n>>> d.values()\n['honderd', 'tien', 'duizend']\n>>> d.items()\n[(100, 'honderd'), (10, 'tien'), (1000, 'duizend')]\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 861, "url": "https://docs.python.org/{python_version}/tut/node86.html"} {"title": "10.9 Miscellaneous New Built-in Functions", "text": "node88.html node65.html node86.html node1.html\n---\n# 10.9 Miscellaneous New Built-in Functions\nThe function `vars()` returns a dictionary containing the current\nlocal variables. With a module argument, it returns that module's\nglobal variables. The old function `dir(x)` returns\n`vars(x).keys()`.\nThe function `round(x)` returns a floating point number rounded\nto the nearest integer (but still expressed as a floating point\nnumber). E.g. `round(3.4) == 3.0` and `round(3.5) == 4.0`.\nWith a second argument it rounds to the specified number of digits,\ne.g. `round(math.pi, 4) == 3.1416` or even\n`round(123.4, -2) == 100.0`.\nThe function `hash(x)` returns a hash value for an object.\nAll object types acceptable as dictionary keys have a hash value (and\nit is this hash value that the dictionary implementation uses).\nThe function `id(x)` return a unique identifier for an object.\nFor two objects x and y, `id(x) == id(y)` if and only if\n`x is y`. (In fact the object's address is used.)\nThe function `hasattr(x, name)` returns whether an object has an\nattribute with the given name (a string value). The function\n`getattr(x, name)` returns the object's attribute with the given\nname. The function `setattr(x, name, value)` assigns a value to\nan object's attribute with the given name. These three functions are\nuseful if the attribute names are not known beforehand. Note that\n`getattr(x, 'spam')` is equivalent to `x.spam`, and\n`setattr(x, 'spam', y)` is equivalent to `x.spam = y`. By\ndefinition, `hasattr(x, name)` returns true if and only if\n`getattr(x, name)` returns without raising an exception.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1630, "url": "https://docs.python.org/{python_version}/tut/node87.html"} {"title": "10.10 Else Clause For Try Statement", "text": "node89.html node65.html node87.html node1.html\n---\n# 10.10 Else Clause For Try Statement\nThe `try...except` statement now has an optional `else`\nclause, which must follow all `except` clauses. It is useful to\nplace 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```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 491, "url": "https://docs.python.org/{python_version}/tut/node88.html"} {"title": "10.11 New Class Features in Release 1.1", "text": "node90.html node65.html node88.html node1.html\n---\n# 10.11 New Class Features in Release 1.1\nSome changes have been made to classes: the operator overloading\nmechanism is more flexible, providing more support for non-numeric use\nof operators (including calling an object as if it were a function),\nand it is possible to trap attribute accesses.\n---\n- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)\n10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)\n10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 610, "url": "https://docs.python.org/{python_version}/tut/node89.html"} {"title": "2.1.2 Interactive Mode", "text": "node10.html node7.html node8.html node1.html\n---\n## 2.1.2 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 (...). Typing an EOF character\n(Control-D on Unix, Control-Z on DOS or Windows)\nat the primary prompt causes the interpreter to exit with a zero exit\nstatus.\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.4 (Oct 25 1996) [GCC 2.7.2]\nCopyright 1991-1996 Stichting Mathematisch Centrum, Amsterdam\n>>>\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 793, "url": "https://docs.python.org/{python_version}/tut/node9.html"} {"title": "10.11.1 New Operator Overloading", "text": "node91.html node89.html node89.html node1.html\n---\n## 10.11.1 New Operator Overloading\nIt is no longer necessary to coerce both sides of an operator to the\nsame class or type. A class may still provide a `__coerce__`\nmethod, but this method may return objects of different types or\nclasses if it feels like it. If no `__coerce__` is defined, any\nargument type or class is acceptable.\nIn order to make it possible to implement binary operators where the\nright-hand side is a class instance but the left-hand side is not,\nwithout using coercions, right-hand versions of all binary operators\nmay be defined. These have an `r' prepended to their name,\ne.g. `__radd__`.\nFor example, here's a very simple class for representing times. Times\nare initialized from a number of seconds (like time.time()). Times\nare printed like this: `Wed Mar 15 12:28:48 1995`. Subtracting\ntwo Times gives their difference in seconds. Adding or subtracting a\nTime and a number gives a new Time. You can't add two times, nor can\nyou subtract a Time from a number.\n```text\nimport time\n\nclass Time:\ndef __init__(self, seconds):\nself.seconds = seconds\ndef __repr__(self):\nreturn time.ctime(self.seconds)\ndef __add__(self, x):\nreturn Time(self.seconds + x)\n__radd__ = __add__ # support for x+t\ndef __sub__(self, x):\nif hasattr(x, 'seconds'): # test if x could be a Time\nreturn self.seconds - x.seconds\nelse:\nreturn self.seconds - x\n\nnow = Time(time.time())\ntomorrow = 24*3600 + now\nyesterday = now - today\nprint tomorrow - yesterday # prints 172800\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1550, "url": "https://docs.python.org/{python_version}/tut/node90.html"} {"title": "10.11.2 Trapping Attribute Access", "text": "node92.html node89.html node90.html node1.html\n---\n## 10.11.2 Trapping Attribute Access\nYou can define three new ``magic'' methods in a class now:\n`__getattr__(self, name)`, `__setattr__(self, name, value)`\nand `__delattr__(self, name)`.\nThe `__getattr__` method is called when an attribute access fails,\ni.e. when an attribute access would otherwise raise AttributeError --\nthis is after the instance's dictionary and its class hierarchy\nhave been searched for the named attribute. Note that if this method\nattempts to access any undefined instance attribute it will be called\nrecursively!\nThe `__setattr__` and `__delattr__` methods are called when\nassignment to, respectively deletion of an attribute are attempted.\nThey are called instead of the normal action (which is to insert\nor delete the attribute in the instance dictionary). If either of\nthese methods most set or delete any attribute, they can only do so by\nusing the instance dictionary directly -- `self.__dict__` -- else\nthey would be called recursively.\nFor example, here's a near-universal ``Wrapper'' class that passes all\nits attribute accesses to another object. Note how the\n`__init__` method inserts the wrapped object in\n`self.__dict__` in order to avoid endless recursion\n(`__setattr__` would call `__getattr__` which would call\nitself recursively).\n```text\nclass Wrapper:\ndef __init__(self, wrapped):\nself.__dict__['wrapped'] = wrapped\ndef __getattr__(self, name):\nreturn getattr(self.wrapped, name)\ndef __setattr__(self, name, value):\nsetattr(self.wrapped, name, value)\ndef __delattr__(self, name):\ndelattr(self.wrapped, name)\n\nimport sys\nf = Wrapper(sys.stdout)\nf.write('hello world\\n') # prints 'hello world'\n```\nA simpler example of `__getattr__` is an attribute that is\ncomputed each time (or the first time) it it accessed. For instance:\n```text\nfrom math import pi\n\nclass Circle:\ndef __init__(self, radius):\nself.radius = radius\ndef __getattr__(self, name):\nif name == 'circumference':\nreturn 2 * pi * self.radius\nif name == 'diameter':\nreturn 2 * self.radius\nif name == 'area':\nreturn pi * pow(self.radius, 2)\nraise AttributeError, name\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 2152, "url": "https://docs.python.org/{python_version}/tut/node91.html"} {"title": "10.11.3 Calling a Class Instance", "text": "node93.html node89.html node91.html node1.html\n---\n## 10.11.3 Calling a Class Instance\nIf a class defines a method `__call__` it is possible to call its\ninstances as if they were functions. For example:\n```text\nclass PresetSomeArguments:\ndef __init__(self, func, *args):\nself.func, self.args = func, args\ndef __call__(self, *args):\nreturn apply(self.func, self.args + args)\n\nf = PresetSomeArguments(pow, 2) # f(i) computes powers of 2\nfor i in range(10): print f(i), # prints 1 2 4 8 16 32 64 128 256 512\nprint # append newline\n```\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 559, "url": "https://docs.python.org/{python_version}/tut/node92.html"} {"title": "11 New in Release 1.2", "text": "node94.html tut.html node92.html node1.html\n---\n# 11 New in Release 1.2\nThis chapter describes even more recent additions to the Python\nlanguage and library.\n---\n- 11.1 New Class Features (node94.html#SECTION001210000000000000000)\n11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)\n11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)\n11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)\n- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)\n11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)\n11.5 Documentation Strings (node100.html#SECTION001250000000000000000)\n11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)\n11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)\n11.8 Miscellaneous (node103.html#SECTION001280000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 919, "url": "https://docs.python.org/{python_version}/tut/node93.html"} {"title": "11.1 New Class Features", "text": "node95.html node93.html node93.html node1.html\n---\n# 11.1 New Class Features\nThe semantics of `__coerce__` have been changed to be more\nreasonable. As an example, the new standard module `Complex`\nimplements fairly complete complex numbers using this. Additional\nexamples of classes with and without `__coerce__` methods can be\nfound in the `Demo/classes` subdirectory, modules `Rat` and\n`Dates`.\nIf a class defines no `__coerce__` method, this is equivalent to\nthe following definition:\n```text\ndef __coerce__(self, other): return self, other\n```\nIf `__coerce__` coerces itself to an object of a different type,\nthe operation is carried out using that type -- in release 1.1, this\nwould cause an error.\nComparisons involving class instances now invoke `__coerce__`\nexactly as if `cmp(x, y)` were a binary operator like `+`\n(except if `x` and `y` are the same object).\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 896, "url": "https://docs.python.org/{python_version}/tut/node94.html"} {"title": "11.2 Unix Signal Handling", "text": "node96.html node93.html node94.html node1.html\n---\n# 11.2 Unix Signal Handling\nOn Unix, Python now supports signal handling. The module\n`signal` exports functions `signal`, `pause` and\n`alarm`, which act similar to their Unix counterparts. The\nmodule also exports the conventional names for the various signal\nclasses (also usable with `os.kill()`) and `SIG_IGN` and\n`SIG_DFL`. See the section on `signal` in the Library\nReference Manual for more information.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 487, "url": "https://docs.python.org/{python_version}/tut/node95.html"} {"title": "11.3 Exceptions Can Be Classes", "text": "node97.html node93.html node95.html node1.html\n---\n# 11.3 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\n`str()`.\nIn this release, the built-in exceptions are still strings.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1534, "url": "https://docs.python.org/{python_version}/tut/node96.html"} {"title": "11.4 Object Persistency and Object Copying", "text": "node98.html node93.html node96.html node1.html\n---\n# 11.4 Object Persistency and Object Copying\nTwo new modules, `pickle` and `shelve`, support storage and\nretrieval of (almost) arbitrary Python objects on disk, using the\n`dbm` package. A third module, `copy`, provides flexible\nobject copying operations. More information on these modules is\nprovided in the Library Reference Manual.\n---\n- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)\n11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 553, "url": "https://docs.python.org/{python_version}/tut/node97.html"} {"title": "11.4.1 Persistent Objects", "text": "node99.html node97.html node97.html node1.html\n---\n## 11.4.1 Persistent Objects\nThe module `pickle` provides a general framework for objects to\ndisassemble themselves into a stream of bytes and to reassemble such a\nstream back into an object. It copes with reference sharing,\nrecursive objects and instances of user-defined classes, but not\n(directly) with objects that have ``magical'' links into the operating\nsystem such as open files, sockets or windows.\nThe `pickle` module defines a simple protocol whereby\nuser-defined classes can control how they are disassembled and\nassembled. The method `__getinitargs__()`, if defined, returns\nthe argument list for the constructor to be used at assembly time (by\ndefault the constructor is called without arguments). The methods\n`__getstate__()` and `__setstate__()` are used to pass\nadditional state from disassembly to assembly; by default the\ninstance's `__dict__` is passed and restored.\nNote that `pickle` does not open or close any files -- it can be\nused equally well for moving objects around on a network or store them\nin a database. For ease of debugging, and the inevitable occasional\nmanual patch-up, the constructed byte streams consist of printable\nASCII characters only (though it's not designed to be pretty).\nThe module `shelve` provides a simple model for storing objects\non files. The operation `shelve.open(filename)` returns a\n``shelf'', which is a simple persistent database with a\ndictionary-like interface. Database keys are strings, objects stored\nin the database can be anything that `pickle` will handle.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 1605, "url": "https://docs.python.org/{python_version}/tut/node98.html"} {"title": "11.4.2 Copying Objects", "text": "node100.html node97.html node98.html node1.html\n---\n## 11.4.2 Copying Objects\nThe module `copy` exports two functions: `copy()` and\n`deepcopy()`. The `copy()` function returns a ``shallow''\ncopy of an object; `deepcopy()` returns a ``deep'' copy. The\ndifference 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 the same objects into in that the\noriginal contains.A deep copy constructs a new compound object and then, recursively,\ninserts copies into it of the objects found in the original.\nBoth functions have the same restrictions and use the same protocols\nas `pickle` -- user-defined classes can control how they are\ncopied by providing methods named `__getinitargs__()`,\n`__getstate__()` and `__setstate__()`.\n---\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 926, "url": "https://docs.python.org/{python_version}/tut/node99.html"} {"title": "Python Tutorial", "text": "node1.html node1.html\n---\n# Python Tutorial\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\nOctober 25, 1996\nRelease 1.4\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 a simple, yet powerful programming language that bridges the\ngap between C and shell programming, and is thus ideally suited for\n``throw-away programming''\nand rapid prototyping. Its syntax is put\ntogether from constructs borrowed from a variety of other languages;\nmost prominent are influences from ABC, C, Modula-3 and Icon.\nThe Python interpreter is easily extended with new functions and data\ntypes implemented in C. Python is also suitable as an extension\nlanguage for highly customizable C applications such as editors or\nwindow managers.\nPython is available for various operating systems, amongst which\nseveral flavors of Unix, the Apple Macintosh, MS-DOS, Windows\n(3.1(1), '95 and NT flavors), OS/2, and others.\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 as the examples\nare self-contained, the tutorial can be read off-line as well.\nFor a description of standard objects and modules, see the Python\nLibrary Reference document. The Python Reference Manual gives\na more formal definition of the language.\n---\n- Contents (node1.html#SECTION00100000000000000000)\n1 Whetting Your Appetite (node2.html#SECTION00200000000000000000)\n- 1.1 Disclaimer (node3.html#SECTION00210000000000000000)\n1.2 Introduction (node4.html#SECTION00220000000000000000)\n1.3 Where From Here (node5.html#SECTION00230000000000000000)\n2 Using the Python Interpreter (node6.html#SECTION00300000000000000000)\n- 2.1 Invoking the Interpreter (node7.html#SECTION00310000000000000000)\n- 2.1.1 Argument Passing (node8.html#SECTION00311000000000000000)\n2.1.2 Interactive Mode (node9.html#SECTION00312000000000000000)\n2.2 The Interpreter and its Environment (node10.html#SECTION00320000000000000000)\n- 2.2.1 Error Handling (node11.html#SECTION00321000000000000000)\n2.2.2 The Module Search Path (node12.html#SECTION00322000000000000000)\n2.2.3 ``Compiled'' Python files (node13.html#SECTION00323000000000000000)\n2.2.4 Executable Python scripts (node14.html#SECTION00324000000000000000)\n2.2.5 The Interactive Startup File (node15.html#SECTION00325000000000000000)\n2.3 Interactive Input Editing and History Substitution (node16.html#SECTION00330000000000000000)\n- 2.3.1 Line Editing (node17.html#SECTION00331000000000000000)\n2.3.2 History Substitution (node18.html#SECTION00332000000000000000)\n2.3.3 Key Bindings (node19.html#SECTION00333000000000000000)\n2.3.4 Commentary (node20.html#SECTION00334000000000000000)\n3 An Informal Introduction to Python (node21.html#SECTION00400000000000000000)\n- 3.1 Using Python as a Calculator (node22.html#SECTION00410000000000000000)\n- 3.1.1 Numbers (node23.html#SECTION00411000000000000000)\n3.1.2 Strings (node24.html#SECTION00412000000000000000)\n3.1.3 Lists (node25.html#SECTION00413000000000000000)\n3.2 First Steps Towards Programming (node26.html#SECTION00420000000000000000)\n4 More Control Flow Tools (node27.html#SECTION00500000000000000000)\n- 4.1 If Statements (node28.html#SECTION00510000000000000000)\n4.2 For Statements (node29.html#SECTION00520000000000000000)\n4.3 The range() Function (node30.html#SECTION00530000000000000000)\n4.4 Break and Continue Statements, and Else Clauses on Loops (node31.html#SECTION00540000000000000000)\n4.5 Pass Statements (node32.html#SECTION00550000000000000000)\n4.6 Defining Functions (node33.html#SECTION00560000000000000000)\n5 Odds and Ends (node34.html#SECTION00600000000000000000)\n- 5.1 More on Lists (node35.html#SECTION00610000000000000000)\n5.2 The del statement (node36.html#SECTION00620000000000000000)\n5.3 Tuples and Sequences (node37.html#SECTION00630000000000000000)\n5.4 Dictionaries (node38.html#SECTION00640000000000000000)\n5.5 More on Conditions (node39.html#SECTION00650000000000000000)\n5.6 Comparing Sequences and Other Types (node40.html#SECTION00660000000000000000)\n6 Modules (node41.html#SECTION00700000000000000000)\n- 6.1 More on Modules (node42.html#SECTION00710000000000000000)\n6.2 Standard Modules (node43.html#SECTION00720000000000000000)\n6.3 The dir() function (node44.html#SECTION00730000000000000000)\n7 Output Formatting (node45.html#SECTION00800000000000000000)\n8 Errors and Exceptions (node46.html#SECTION00900000000000000000)\n- 8.1 Syntax Errors (node47.html#SECTION00910000000000000000)\n8.2 Exceptions (node48.html#SECTION00920000000000000000)\n8.3 Handling Exceptions (node49.html#SECTION00930000000000000000)\n8.4 Raising Exceptions (node50.html#SECTION00940000000000000000)\n8.5 User-defined Exceptions (node51.html#SECTION00950000000000000000)\n8.6 Defining Clean-up Actions (node52.html#SECTION00960000000000000000)\n9 Classes (node53.html#SECTION001000000000000000000)\n- 9.1 A word about terminology (node54.html#SECTION001010000000000000000)\n9.2 Python scopes and name spaces (node55.html#SECTION001020000000000000000)\n9.3 A first look at classes (node56.html#SECTION001030000000000000000)\n- 9.3.1 Class definition syntax (node57.html#SECTION001031000000000000000)\n9.3.2 Class objects (node58.html#SECTION001032000000000000000)\n9.3.3 Instance objects (node59.html#SECTION001033000000000000000)\n9.3.4 Method objects (node60.html#SECTION001034000000000000000)\n9.4 Random remarks (node61.html#SECTION001040000000000000000)\n9.5 Inheritance (node62.html#SECTION001050000000000000000)\n- 9.5.1 Multiple inheritance (node63.html#SECTION001051000000000000000)\n9.6 Odds and ends (node64.html#SECTION001060000000000000000)\n10 Recent Additions as of Release 1.1 (node65.html#SECTION001100000000000000000)\n- 10.1 The Last Printed Expression (node66.html#SECTION001110000000000000000)\n10.2 String Literals (node67.html#SECTION001120000000000000000)\n- 10.2.1 Double Quotes (node68.html#SECTION001121000000000000000)\n10.2.2 Continuation Of String Literals (node69.html#SECTION001122000000000000000)\n10.2.3 Triple-quoted strings (node70.html#SECTION001123000000000000000)\n10.2.4 String Literal Juxtaposition (node71.html#SECTION001124000000000000000)\n10.3 The Formatting Operator (node72.html#SECTION001130000000000000000)\n- 10.3.1 Basic Usage (node73.html#SECTION001131000000000000000)\n10.3.2 Referencing Variables By Name (node74.html#SECTION001132000000000000000)\n10.4 Optional Function Arguments (node75.html#SECTION001140000000000000000)\n- 10.4.1 Default Argument Values (node76.html#SECTION001141000000000000000)\n10.4.2 Arbitrary Argument Lists (node77.html#SECTION001142000000000000000)\n10.5 Lambda And Functional Programming Tools (node78.html#SECTION001150000000000000000)\n- 10.5.1 Lambda Forms (node79.html#SECTION001151000000000000000)\n10.5.2 Map, Reduce and Filter (node80.html#SECTION001152000000000000000)\n10.6 Continuation Lines Without Backslashes (node84.html#SECTION001160000000000000000)\n10.7 Regular Expressions (node85.html#SECTION001170000000000000000)\n10.8 Generalized Dictionaries (node86.html#SECTION001180000000000000000)\n10.9 Miscellaneous New Built-in Functions (node87.html#SECTION001190000000000000000)\n10.10 Else Clause For Try Statement (node88.html#SECTION0011100000000000000000)\n10.11 New Class Features in Release 1.1 (node89.html#SECTION0011110000000000000000)\n- 10.11.1 New Operator Overloading (node90.html#SECTION0011111000000000000000)\n10.11.2 Trapping Attribute Access (node91.html#SECTION0011112000000000000000)\n10.11.3 Calling a Class Instance (node92.html#SECTION0011113000000000000000)\n11 New in Release 1.2 (node93.html#SECTION001200000000000000000)\n- 11.1 New Class Features (node94.html#SECTION001210000000000000000)\n11.2 Unix Signal Handling (node95.html#SECTION001220000000000000000)\n11.3 Exceptions Can Be Classes (node96.html#SECTION001230000000000000000)\n11.4 Object Persistency and Object Copying (node97.html#SECTION001240000000000000000)\n- 11.4.1 Persistent Objects (node98.html#SECTION001241000000000000000)\n11.4.2 Copying Objects (node99.html#SECTION001242000000000000000)\n11.5 Documentation Strings (node100.html#SECTION001250000000000000000)\n11.6 Customizing Import and Built-Ins (node101.html#SECTION001260000000000000000)\n11.7 Python and the World-Wide Web (node102.html#SECTION001270000000000000000)\n11.8 Miscellaneous (node103.html#SECTION001280000000000000000)\n12 New in Release 1.3 (node104.html#SECTION001300000000000000000)\n- 12.1 Keyword Arguments (node105.html#SECTION001310000000000000000)\n12.2 Changes to the WWW and Internet tools (node106.html#SECTION001320000000000000000)\n12.3 Other Language Changes (node107.html#SECTION001330000000000000000)\n12.4 Changes to Built-in Operations (node108.html#SECTION001340000000000000000)\n12.5 Library Changes (node109.html#SECTION001350000000000000000)\n12.6 Other Changes (node110.html#SECTION001360000000000000000)\n13 New in Release 1.4 (node111.html#SECTION001400000000000000000)\n- 13.1 Language Changes (node112.html#SECTION001410000000000000000)\n13.2 Run-time Changes (node113.html#SECTION001420000000000000000)\n13.3 New or Updated Modules (node114.html#SECTION001430000000000000000)\n13.4 Configuration and Installation (node115.html#SECTION001440000000000000000)\nAbout this document ... (node116.html#SECTION001500000000000000000)\n---\nnode1.html node1.html\nguido@cnri.reston.va.us", "python_version": "1.4", "length": 10704, "url": "https://docs.python.org/{python_version}/tut/tut.html"}