2697 lines
165 KiB
HTML
2697 lines
165 KiB
HTML
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
|
|
<html>
|
|
<head>
|
|
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
|
|
<meta name="GENERATOR" content="Mozilla/4.5 [fr] (WinNT; I) [Netscape]">
|
|
<title>A Python Quick Reference</title>
|
|
<link rev="made" href="mailto:derek@cc.bellcore.com (Derek Fields)">
|
|
</head>
|
|
<body>
|
|
|
|
<center>
|
|
<h1>
|
|
Python 1.52 Quick Reference</h1></center>
|
|
|
|
<hr>
|
|
<br><font size=-1> <i>1999/06/04, upgraded by Richard Gruet, <a href="mailto:rgruet@ina.fr">rgruet@ina.fr</a>
|
|
from V1.3 ref: 1995/10/30, by Chris Hoffmann, <a href="mailto:choffman@vicorp.com">choffman@vicorp.com</a></i></font>
|
|
<p><font size=-1>Based on:</font>
|
|
<br><font size=-1> Python Bestiary, Author: Ken Manheimer,
|
|
ken.manheimer@nist.gov</font>
|
|
<br><font size=-1> Python manuals, Author: Guido van
|
|
Rossum, <a href="mailto:guido@CNRI.Reston.Va.US">guido@CNRI.Reston.Va.US</a>,
|
|
<a href="mailto:guido@python.org">guido@python.org</a></font>
|
|
<br><font size=-1> python-mode.el, Author: Tim Peters,
|
|
<a href="mailto:tim_one@email.msn.com">tim_one@email.msn.com</a></font>
|
|
<br><font size=-1> and the readers of <a href="news:comp.lang.python">comp.lang.python</a></font>
|
|
<p><font size=-1>Python site: <a href="http://www.python.org/">http://www.python.org</a></font>
|
|
<br>
|
|
<hr>
|
|
<h2>
|
|
Contents</h2>
|
|
|
|
<menu>
|
|
<li>
|
|
<a href="#Invocation">Invocation Options</a></li>
|
|
|
|
<li>
|
|
<a href="#Environment">Environment Variables</a></li>
|
|
|
|
<li>
|
|
<a href="#Terms">Terms Used In This Document</a></li>
|
|
|
|
<li>
|
|
<a href="#LexEnt">Lexical Entities</a></li>
|
|
|
|
<li>
|
|
<a href="#BasicTypes">Basic Types And Their Operations</a></li>
|
|
|
|
<li>
|
|
<a href="#AdvTypes">Advanced Types</a></li>
|
|
|
|
<li>
|
|
<a href="#Statements">Statements</a></li>
|
|
|
|
<li>
|
|
<a href="#BuiltIn">Built In Functions</a></li>
|
|
|
|
<li>
|
|
<a href="#BuiltInExc">Built In Exceptions</a></li>
|
|
|
|
<li>
|
|
<a href="#SpecialMethods">Standard methods & operators redefinition
|
|
in user-created Classes</a></li>
|
|
|
|
<li>
|
|
<a href="#typeAttributes">Special informative state attributes for some
|
|
types</a></li>
|
|
|
|
<li>
|
|
<a href="#ImportantModules">Important Modules</a> : <a href="#sysModule">sys</a>,
|
|
<a href="#osModule">os</a>,
|
|
<a href="#posixModule">posix</a>,
|
|
<a href="#posixpathModule">posixpath</a>,
|
|
<a href="#stringModule">string</a>,
|
|
<a href="#reModule">re</a>,
|
|
<a href="#mathModule">math</a>,
|
|
<a href="#getoptModule">getopt</a></li>
|
|
|
|
<li>
|
|
<a href="#OtherModules">List of modules In base distribution</a></li>
|
|
|
|
<li>
|
|
<a href="#Workspace">Workspace Exploration And Idiom Hints</a></li>
|
|
|
|
<li>
|
|
<a href="#Emacs">Python Mode for Emacs</a></li>
|
|
|
|
<li>
|
|
<a href="#Debugger">The Python Debugger</a></li>
|
|
</menu>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="Invocation"></a>Invocation Options</h2>
|
|
|
|
<pre><b>python</b> [-diOStuvxX?] [-c <i>command</i> | <i>script</i> | - ] [<i>args</i>]
|
|
|
|
-d debug output from parser (also PYTHONDEBUG=x)
|
|
-i inspect interactively after running script (also PYTHONINSPECT=x,.
|
|
and force prompts, even if stdin appears not to be a terminal
|
|
-O optimize generated bytecode (set __debug__ = 0 =>s suppresses <i>assert</i>s)
|
|
-S don't imply 'import site' on initialization
|
|
-t issue warnings about inconsistent tab usage (-tt: issue errors)
|
|
-u unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
|
|
-v verbose (trace import statements) (also PYTHONVERBOSE=x)
|
|
-x skip first line of source, allowing use of non-unix
|
|
forms of #!cmd
|
|
-X disable class based built-in exceptions (for backward
|
|
compatibility management of exceptions)
|
|
-? Help!
|
|
|
|
-c <i>command
|
|
</i>Specify the command to execute (see next section).
|
|
This terminates the option list (following options are
|
|
passed as arguments to the command).
|
|
<i>script</i> is the name of a python file (.py) to execute
|
|
- read from stdin.
|
|
|
|
anything afterward is passed as options to python script or
|
|
command, not interpreted as an option to interpreter itself.
|
|
|
|
<i>args</i> are passed to script or command (in sys.argv[1:])</pre>
|
|
If no script or command, Python enters interactive mode.
|
|
<hr>
|
|
<h2>
|
|
<a NAME="Environment"></a>ENVIRONMENT VARIABLES</h2>
|
|
|
|
<dl>
|
|
<dt>
|
|
PYTHONHOME</dt>
|
|
|
|
<br> Alternate <i>prefix</i>
|
|
directory (or <i>prefix</i>;<i>exec_prefix</i>). The default module search
|
|
path uses <i>prefix</i>/lib
|
|
<br>PYTHONPATH
|
|
<dd>
|
|
Augments the default search path for module files. The format is
|
|
the same as the shell's $PATH: one or more directory pathnames separated
|
|
by ':' or ';' without spaces around (semi-)colons!</dd>
|
|
|
|
<dd>
|
|
On Windows first search for Registry key HKEY_LOCAL_MACHINE\Software\Python\PythonCore\v.x.y\PythonPath</dd>
|
|
|
|
<br>(default value). You may also define a key named after your application
|
|
with a default string value giving
|
|
<br>the root directory path of your app.
|
|
<dt>
|
|
PYTHONSTARTUP</dt>
|
|
|
|
<dd>
|
|
If this is the name of a readable file, the Python commands in that
|
|
file are executed before the first prompt is displayed in interactive mode
|
|
(no default).</dd>
|
|
|
|
<dt>
|
|
PYTHONDEBUG</dt>
|
|
|
|
<dd>
|
|
If non-empty, same as -d option</dd>
|
|
|
|
<dt>
|
|
PYTHONINSPECT</dt>
|
|
|
|
<dd>
|
|
If non-empty, same as -i option</dd>
|
|
|
|
<dt>
|
|
PYTHONSUPPRESS</dt>
|
|
|
|
<dd>
|
|
If non-empty, same as -s option</dd>
|
|
|
|
<dt>
|
|
PYTHONUNBUFFERED</dt>
|
|
|
|
<dd>
|
|
If non-empty, same as -u option</dd>
|
|
|
|
<dt>
|
|
PYTHONVERBOSE</dt>
|
|
|
|
<dd>
|
|
If non-empty, same as -v option</dd>
|
|
|
|
<dt>
|
|
PYTHONCASEOK --to be verified--</dt>
|
|
|
|
<dd>
|
|
If non-empty, ignore case in file/module names (imports)</dd>
|
|
</dl>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="Terms"></a>Terms Used In This Document</h2>
|
|
|
|
<dl COMPACT>
|
|
<dt>
|
|
<i>sequence</i></dt>
|
|
|
|
<dd>
|
|
a string, list or tuple</dd>
|
|
|
|
<dt>
|
|
<i>suite</i></dt>
|
|
|
|
<dd>
|
|
a series of statements, possibly separated by newlines. Must all be at
|
|
same indentation level, except for suites inside compound statements</dd>
|
|
|
|
<dt>
|
|
<x></dt>
|
|
|
|
<dd>
|
|
in a syntax diagram means a token referred to as "x"</dd>
|
|
|
|
<dt>
|
|
[xxx]</dt>
|
|
|
|
<dd>
|
|
in a syntax diagram means "xxx" is optional</dd>
|
|
|
|
<dt>
|
|
x ==> y</dt>
|
|
|
|
<dd>
|
|
means the value of <x> is <y></dd>
|
|
|
|
<dt>
|
|
x <=> y</dt>
|
|
|
|
<dd>
|
|
means "x is equivalent to y"</dd>
|
|
</dl>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="LexEnt"></a>Notable lexical entities</h2>
|
|
|
|
<h3>
|
|
Keywords</h3>
|
|
|
|
<blockquote>
|
|
<pre>and del for is raise
|
|
assert elif from lambda return
|
|
break else global not try
|
|
class except if or while
|
|
continue exec import pass
|
|
def finally in print</pre>
|
|
</blockquote>
|
|
|
|
<ul>
|
|
<li>
|
|
(list of keywords in std module: keyword.py)</li>
|
|
|
|
<li>
|
|
Illegitimate Tokens (only valid in strings): @ $ ?</li>
|
|
|
|
<li>
|
|
A statement must all be on a single line. To break a statement over multiple
|
|
lines use "\", as with the C preprocessor. Exception: can always break
|
|
when inside any (), [], or {} pair, or in triple-quoted strings.</li>
|
|
|
|
<li>
|
|
More than one statement can appear on a line if they are separated with
|
|
semicolons (";").</li>
|
|
|
|
<li>
|
|
Comments start with "#" and continue to end of line.</li>
|
|
</ul>
|
|
|
|
<h3>
|
|
Identifiers</h3>
|
|
(letter | "_") (letter
|
|
| digit | "_")*
|
|
<ul>
|
|
<li>
|
|
Python identifiers keywords, attributes, etc. are <b>case-sensitive</b>.</li>
|
|
|
|
<li>
|
|
Special forms: <b>_</b><i>ident</i> (not imported by 'from module import
|
|
*'); <b>__</b><i>ident</i><b>__</b> (system defined name);</li>
|
|
|
|
<br> <b>__</b><i>ident</i>
|
|
(class-private name mangling)</ul>
|
|
|
|
<h3>
|
|
Operators</h3>
|
|
|
|
<blockquote> + -
|
|
* **
|
|
/ %
|
|
<br><< >>
|
|
& |
|
|
^ ~
|
|
<br>< >
|
|
<= >= ==
|
|
!= <></blockquote>
|
|
|
|
<h3>
|
|
Strings</h3>
|
|
<b>"</b>a string enclosed by double quotes<b>"</b>
|
|
<br><b>'</b>another string delimited by single quotes and with a " inside<b>'</b>
|
|
<br><b>'''</b>a string containing embedded newlines and quote (') marks,
|
|
can be
|
|
<br>delimited with triple quotes.<b>'''</b>
|
|
<br>""" may also use 3- double quotes as delimiters """
|
|
<br><b>r'</b>a raw string where \ are kept (literalized): handy for regular
|
|
expressions and windows paths!<b>'</b>
|
|
<br><b>R"</b>another raw string<b>" --</b> raw strings
|
|
cannot end with a \
|
|
<ul>
|
|
<li>
|
|
Use <b>\</b> at end of line to continue a string on next line.</li>
|
|
|
|
<li>
|
|
adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as
|
|
'Monty Python'.</li>
|
|
</ul>
|
|
|
|
<h4>
|
|
String Literal Escapes</h4>
|
|
|
|
<pre> <b>\<i>newline</i></b> Ignored (escape newline)
|
|
<b>\\</b> Backslash (\) <b>\e</b> Escape (ESC) <b>\v</b> Vertical Tab (VT)
|
|
<b>\'</b> Single quote (') <b>\f</b> Formfeed (FF) <b>\0OO</b> (zero) char with
|
|
<b>\"</b> Double quote (") <b>\n</b> Linefeed (LF) octal value OO
|
|
<b>\a</b> Bell (BEL) <b>\r</b> Carriage Return (CR) <b>\xXX</b> char with
|
|
<b>\b</b> Backspace (BS) <b>\t</b> Horizontal Tab (TAB) hex value XX
|
|
<b>\<i>AnyOtherChar</i></b> is left as-is</pre>
|
|
|
|
<ul>
|
|
<li>
|
|
NULL byte (\000) is NOT an end-of-string marker; NULL's may be embedded
|
|
in strings.</li>
|
|
|
|
<li>
|
|
Strings (and tuples) are <u>immutable</u>: they cannot be modified.</li>
|
|
</ul>
|
|
|
|
<h3>
|
|
Numbers</h3>
|
|
Decimal integer: 1234, 1234567890546378940<b>L</b>
|
|
(or <b>l)</b>
|
|
<br>Octal integer: <b>0</b>177, <b>0</b>177777777777777777L (begin with
|
|
a <b>0</b>)
|
|
<br>Hex integer: <b>0x</b>FF, <b>0X</b>FFFFffffFFFFFFFFFFL (begin with
|
|
<b>0x</b>
|
|
or <b>0X</b>)
|
|
<br>Long integer (unlimited precision): 1234567890123456<b>L</b> (ends
|
|
with <b>L</b> or<b> l</b>)
|
|
<br>Float (double precision): 3<b>.</b>14<b>e-10</b>, .001, 10., 1E3
|
|
<br>Complex: 1<b>J</b>, 2<b>+</b>3<b>J</b>, 4<b>+</b>5<b>j </b>(ends with
|
|
<b>J</b>
|
|
or <b>j, +</b> separates real and imaginary parts which are both floats)
|
|
<h3>
|
|
Sequences</h3>
|
|
|
|
<ul>
|
|
<li>
|
|
<u>String</u> of length 0, 1, 2 (see above)</li>
|
|
|
|
<br>'', '1', "12"
|
|
<li>
|
|
<u>Tuple</u> of length 0, 1, 2, etc:</li>
|
|
|
|
<br><b>()</b> (1,) (1,2) # parentheses are optional
|
|
if len > 0
|
|
<li>
|
|
<u>List</u> of length 0, 1, 2, etc:</li>
|
|
|
|
<br><b>[]</b> [1] [1,2]</ul>
|
|
Indexing is 0-based. Negative indices (usually) mean count backwards from
|
|
end of sequence.
|
|
<p>Sequence <u>slicing</u><b> [</b><i>starting-at-index</i> <b>: </b><i>but-less-than-index</i><b>].
|
|
</b>Start
|
|
defaults to '0'; End defaults to 'sequence-length'.
|
|
<ul>a = (0,1,2,3,4,5,6,7)
|
|
<br>a[3] ==> 3
|
|
<br>a[-1] ==> 7
|
|
<br>a[2:4] ==> (2, 3)
|
|
<br>a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
|
|
<br>a[:3] ==> (0, 1, 2)
|
|
<br>a[:] ==> (0,1,2,3,4,5,6,7) # makes a <b>copy</b> of the sequence.</ul>
|
|
|
|
<h3>
|
|
Dictionaries (Mappings)</h3>
|
|
<u>Dictionary</u> of length 0, 1, 2, etc:
|
|
<br><b>{}</b> {1 : 'first'} {1 : 'first', 'next': 'second'}
|
|
<p>
|
|
<hr>
|
|
<h2>
|
|
<a NAME="BasicTypes"></a>Basic Types and Their Operations</h2>
|
|
|
|
<h3>
|
|
Comparisons (defined between *any* types)</h3>
|
|
|
|
<pre> < strictly less than
|
|
<= less than or equal
|
|
> strictly greater than
|
|
>= greater than or equal
|
|
== equal
|
|
!= not equal ( "<>" is also allowed)
|
|
is object identity (are <b>objects</b> identical, not values)
|
|
is not negated object identity</pre>
|
|
X < Y < Z < W has expected meaning, unlike C
|
|
<h3>
|
|
Boolean values and operators</h3>
|
|
|
|
<pre> <b>False</b> values: None, numeric zeros, empty sequences and mappings
|
|
<b>True</b> values: all other values
|
|
|
|
<b>not</b> X: if X is false then 1, else 0
|
|
X <b>or</b> Y: if X is false then Y, else X
|
|
X <b>and</b> Y: if X is false then X, else Y
|
|
|
|
('or', 'and' evaluate second arg only if necessary to determine outcome)</pre>
|
|
|
|
<h3>
|
|
None</h3>
|
|
None is used as default return value on functions.
|
|
<br>Input that evaluates to None does not print when running Python interactively.
|
|
<h3>
|
|
Numeric types</h3>
|
|
|
|
<h4>
|
|
Floats, integers and long integers.</h4>
|
|
Floats are implemented with C doubles.
|
|
<br>Integers are implemented with C longs.
|
|
<br>Long integers have unlimited size (only limit is system resources)
|
|
<h4>
|
|
Operators on all numeric types</h4>
|
|
|
|
<pre> <b>abs</b>(x) absolute value of x
|
|
<b>int</b>(x) x converted to integer
|
|
<b>long</b>(x) x converted to long integer
|
|
<b>float</b>(x) x converted to floating point
|
|
<b>-</b>x x negated
|
|
<b>+</b>x x unchanged
|
|
x <b>+</b> y sum of x and y
|
|
x <b>-</b> y difference of x and y
|
|
x <b>*</b> y product of x and y
|
|
x <b>/</b> y quotient of x and y
|
|
x <b>%</b> y remainder of x / y
|
|
<b>divmod</b>(x, y) the tuple (x/y, x%y)
|
|
x <b>**</b> y x to the power y [same as: <b>pow</b>(x,y)]</pre>
|
|
|
|
<h4>
|
|
Bit operators on integers and long integers</h4>
|
|
|
|
<pre> <b>~</b>x the bits of x inverted
|
|
x <b>^</b> y bitwise exclusive or of x and y
|
|
x <b>&</b> y bitwise and of x and y
|
|
x <b>|</b> y bitwise or of x and y
|
|
x <b><<</b> n x shifted left by n bits
|
|
x <b>>></b> n x shifted right by n bits</pre>
|
|
|
|
<h4>
|
|
Complex Numbers</h4>
|
|
represented as a pair of machine-level double precision floating point
|
|
numbers.
|
|
<br>The real and imaginary value of a complex number z can be retrieved
|
|
through the
|
|
<br>attributes <u>z.real</u> and <u>z.imag</u>.
|
|
<h4>
|
|
Numeric exceptions</h4>
|
|
|
|
<dl COMPACT>
|
|
<dt>
|
|
TypeError</dt>
|
|
|
|
<dd>
|
|
raised on application of arithmetic operation to non-number</dd>
|
|
|
|
<dt>
|
|
OverflowError</dt>
|
|
|
|
<dd>
|
|
numeric bounds exceeded</dd>
|
|
|
|
<dt>
|
|
ZeroDivisionError</dt>
|
|
|
|
<dd>
|
|
raised when zero second argument of div or modulo op</dd>
|
|
</dl>
|
|
|
|
<h3>
|
|
Operations on all sequence types (lists, tuples, strings)</h3>
|
|
|
|
<center><table BORDER CELLPADDING=3 WIDTH="60%" BGCOLOR="#FFCC99" >
|
|
<tr BGCOLOR="#FFCC99">
|
|
<td><b>Operation</b></td>
|
|
|
|
<td>
|
|
<center><b>Result</b></center>
|
|
</td>
|
|
|
|
<td><b>Notes</b></td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>x</i> <b>in</b> <i>s</i></font></td>
|
|
|
|
<td>1 if an item of <i>s</i> is equal to <i>x</i>, else 0</td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>x</i> <b>not in</b> <i>s</i></font></td>
|
|
|
|
<td>0 if an item of <i>s</i> is equal to <i>x</i>, else 1</td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>s</i> <b>+</b> <i>t</i></font></td>
|
|
|
|
<td>the concatenation of <i>s</i> and <i>t</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>s </i><b>*</b> <i>n</i>, <i>n</i><b>*</b><i>s</i></font></td>
|
|
|
|
<td><i>n</i> copies of <i>s</i> concatenated</td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>s</i><b>[</b><i>i</i><b>]</b></font></td>
|
|
|
|
<td><i>i</i>'th item of <i>s</i>, origin 0</td>
|
|
|
|
<td>
|
|
<center>(1)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><i>s</i><b>[</b><i>i</i><b>:</b><i>j</i><b>]</b></font></td>
|
|
|
|
<td>slice of <i>s</i> from <i>i</i> (included) to <i>j</i> (excluded)</td>
|
|
|
|
<td>
|
|
<center>(1), (2)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><b>len</b>(<i>s</i>)</font></td>
|
|
|
|
<td>length of <i>s</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><b>min</b>(<i>s</i>)</font></td>
|
|
|
|
<td>smallest item of <i>s</i></td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr BGCOLOR="#FFFFCC">
|
|
<td><font face="Courier New,Courier"><b>max</b>(<i>s</i>)</font></td>
|
|
|
|
<td>largest item of <i>(s</i>)</td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
</table></center>
|
|
|
|
<pre><u>Notes</u> :</pre>
|
|
<font size=-1> (1) if <i>i</i> or <i>j</i> is negative,
|
|
the index is relative to the end of the string, ie <font face="Courier New,Courier">len(<i>s</i>)+
|
|
<i>i</i></font>
|
|
or <font face="Courier New,Courier">len(<i>s</i>)+<i>j</i></font> is</font>
|
|
<br><font size=-1> substituted.
|
|
But note that -0 is still 0.</font>
|
|
<br><font size=-1> (2) The slice of <i>s</i> from <i>i</i>
|
|
to <i>j</i> is defined as the sequence of items with index <i>k</i> such
|
|
that <i>i <= k < j</i>.</font>
|
|
<br><font size=-1>
|
|
If <i>i</i> or <i>j</i> is greater than<font face="Courier New,Courier">
|
|
len(<i>s</i>)</font>, use<font face="Courier New,Courier"> len(<i>s</i>)</font>.
|
|
If <i>i</i> is omitted, use len(<i>s</i>). If <i>i</i> is greater than
|
|
or</font>
|
|
<br><font size=-1>
|
|
equal to <i>j</i>, the slice is empty.</font>
|
|
<h3>
|
|
Operations on mutable (=modifiable) sequences (lists)</h3>
|
|
|
|
<center><table BORDER CELLPADDING=3 WIDTH="70%" BGCOLOR="#FFFFCC" >
|
|
<tr BGCOLOR="#FFCC99">
|
|
<td><b>Operation</b></td>
|
|
|
|
<td>
|
|
<center><b>Result</b></center>
|
|
</td>
|
|
|
|
<td><b>Notes</b></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i><b>[</b><i>i</i><b>]</b> <b>=</b><i>x</i></font></td>
|
|
|
|
<td>item <i>i</i> of <i>s</i> is replaced by <i>x</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><i>s</i>[<i>i</i>:<i>j</i>] <b>=</b> <i>t</i></td>
|
|
|
|
<td>slice of <i>s</i> from <i>i</i> to <i>j</i> is replaced by <i>t</i></td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><b>del</b> <i>s</i>[<i>i</i>:<i>j</i>]</font></td>
|
|
|
|
<td>same as <font face="Courier New,Courier"><i>s</i>[<i>i</i>:<i>j</i>]
|
|
= []</font></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>append</b>(<i>x</i>)</font></td>
|
|
|
|
<td>same as <font face="Courier New,Courier"><i>s</i>[len(<i>s</i>) : len(<i>s</i>)]
|
|
= [<i>x</i>]</font></td>
|
|
|
|
<td>
|
|
<center> </center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>extend</b>(<i>x</i>)</font></td>
|
|
|
|
<td>same as <font face="Courier New,Courier"><i>s</i>[len(<i>s</i>):len(<i>s</i>)]=
|
|
<i>x</i></font></td>
|
|
|
|
<td> (5)</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>count</b>(<i>x</i>)</font></td>
|
|
|
|
<td>return number of <i>i</i>'s for which <font face="Courier New,Courier"><i>s</i>[<i>i</i>]
|
|
== <i>x</i></font></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>index</b>(<i>x</i>)</font></td>
|
|
|
|
<td>return smallest <i>i</i> such that <font face="Courier New,Courier"><i>s</i>[<i>i</i>]
|
|
== <i>x</i></font></td>
|
|
|
|
<td>
|
|
<center>(1)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>insert</b>(<i>i</i>, <i>x</i>)</font></td>
|
|
|
|
<td>same as <font face="Courier New,Courier"><i>s</i>[<i>i</i>:<i>i</i>]
|
|
= [<i>x</i>]</font> if <i>i</i> >= 0</td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>remove</b>(<i>x</i>)</font></td>
|
|
|
|
<td>same as <font face="Courier New,Courier">del <i>s</i>[<i>s</i>.index(<i>x</i>)]</font></td>
|
|
|
|
<td>
|
|
<center>(1)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>pop</b>(<b>[</b><i>i</i><b>]</b>)</font></td>
|
|
|
|
<td>same as x = s[i]; del s[i]; return x</td>
|
|
|
|
<td> (4)</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>reverse</b>()</font></td>
|
|
|
|
<td>reverse the items of <i>s</i> in place</td>
|
|
|
|
<td>
|
|
<center>(3)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>s</i>.<b>sort</b>(<b>[</b><i>cmpFct</i><b>]</b>)</font></td>
|
|
|
|
<td>sort the items of <i>s</i> in place</td>
|
|
|
|
<td>
|
|
<center>(2), (3)</center>
|
|
</td>
|
|
</tr>
|
|
</table></center>
|
|
|
|
<p><u>Notes</u> :
|
|
<br> <font size=-1> (1) raise a ValueError exception when
|
|
<i>x</i>
|
|
is not found in <i>s</i> (i.e. out of range).</font>
|
|
<br><font size=-1> (2) The sort() method takes
|
|
an optional argument specifying a comparison fct of 2 arguments (list items)
|
|
which should</font>
|
|
<br><font size=-1>
|
|
return -1, 0, or 1 depending on whether the 1st argument is considered
|
|
smaller than, equal to, or larger than the 2nd</font>
|
|
<br><font size=-1>
|
|
argument. Note that this slows the sorting process down considerably.</font>
|
|
<br><font size=-1> (3) The sort() and reverse()
|
|
methods <b>modify</b> the list <b>in place</b> for economy of space when
|
|
sorting or reversing a large list.</font>
|
|
<br><font size=-1>
|
|
They don't return the sorted or reversed list to remind you of this side
|
|
effect.</font>
|
|
<br><font size=-1> (4) [<i>New 1.5.2</i>] The pop()
|
|
method is experimental and not supported by other mutable sequence types
|
|
than lists.</font>
|
|
<br><font size=-1>
|
|
The optional argument i defaults to -1, so that by default the last
|
|
item is removed and returned.</font>
|
|
<br><font size=-1> (5) [<i>New 1.5.2</i>] Experimental
|
|
! Raises an exception when x is not a list object.</font>
|
|
<br>
|
|
<br>
|
|
<h3>
|
|
Operations on mappings (dictionaries)</h3>
|
|
|
|
<center><table BORDER CELLPADDING=3 WIDTH="70%" BGCOLOR="#FFFFCC" >
|
|
<tr BGCOLOR="#FFCC99">
|
|
<td><b>Operation</b></td>
|
|
|
|
<td>
|
|
<center><b>Result</b></center>
|
|
</td>
|
|
|
|
<td><b>Notes</b></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><b>len</b>(<i>d</i>)</font></td>
|
|
|
|
<td>the number of items in <i>d</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i><b>[</b><i>k</i><b>]</b></font></td>
|
|
|
|
<td>the item of <i>d</i> with key <i>k</i></td>
|
|
|
|
<td>
|
|
<center>(1)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>[<i>k</i>] <b>=</b> x</font></td>
|
|
|
|
<td>set <i>d</i>[<i>k</i>] to <i>x</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><b>del</b> <i>d</i>[<i>k</i>]</font></td>
|
|
|
|
<td>remove <i>d</i>[<i>k</i>] from <i>d</i></td>
|
|
|
|
<td>
|
|
<center>(1)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>clear</b>()</font></td>
|
|
|
|
<td>remove all items from <i>d</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>copy</b>()</font></td>
|
|
|
|
<td>a shallow copy of <i>d</i></td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>has_key</b>(<i>k</i>)</font></td>
|
|
|
|
<td>1 if <i>d</i> has key <i>k</i>, else 0</td>
|
|
|
|
<td></td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>items</b>()</font></td>
|
|
|
|
<td>a copy of <i>d</i>'s list of (key, item) pairs</td>
|
|
|
|
<td>
|
|
<center>(2)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>keys</b>()</font></td>
|
|
|
|
<td>a copy of <i>d</i>'s list of keys</td>
|
|
|
|
<td>
|
|
<center>(2)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d1</i>.<b>update</b>(<i>d2</i>)</font></td>
|
|
|
|
<td><font face="Courier New,Courier">for k, v in d2.items(): d1[k] = v</font></td>
|
|
|
|
<td>
|
|
<center>(3)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>values</b>()</font></td>
|
|
|
|
<td>a copy of <i>d</i>'s list of values</td>
|
|
|
|
<td>
|
|
<center>(2)</center>
|
|
</td>
|
|
</tr>
|
|
|
|
<tr>
|
|
<td><font face="Courier New,Courier"><i>d</i>.<b>get</b>(<i>k</i>,<i>defaultval</i>)</font></td>
|
|
|
|
<td>the item of <i>d</i> with key <i>k</i></td>
|
|
|
|
<td>
|
|
<center>(4)</center>
|
|
</td>
|
|
</tr>
|
|
</table></center>
|
|
|
|
<blockquote>
|
|
<blockquote>
|
|
<blockquote><u>Notes</u> :
|
|
<br><font size=-1> TypeError is raised if key is not acceptable</font>
|
|
<br><font size=-1> (1) KeyError is raised if key k is not in the
|
|
map</font>
|
|
<br><font size=-1> (2) Keys and values are listed in random order</font>
|
|
<br><font size=-1> (3) <i>d2</i> must be of the same type as <i>d1</i></font>
|
|
<br><font size=-1><i> (</i>4) Never raises an exception if <i>k</i>
|
|
is not in the map, instead it returns <i>defaultVal</i>.</font>
|
|
<br><font size=-1><i> defaultVal</i> is optional,
|
|
when not provided and <i>k</i> is not in the map, None is returned.</font></blockquote>
|
|
</blockquote>
|
|
</blockquote>
|
|
|
|
<h3>
|
|
Format operator for strings (%)</h3>
|
|
|
|
<h4>
|
|
<font face="Courier New,Courier">Uses C </font>printf format codes :</h4>
|
|
Supports: %, c, s, i, d, u, o, x, X, e, E, f, g, G.
|
|
<p>Width and precision may be a * to specify that an integer argument specifies
|
|
the actual width or precision.
|
|
<p>The flag characters -, +, blank, # and 0 are understood.
|
|
<p>%s will convert any type argument to string (uses <i>str()</i> function)
|
|
<pre> a = '%s has %03d quote types.' <b>%</b> ('Python', 2)
|
|
a ==> 'Python has 002 quote types.'</pre>
|
|
Right-hand-side can be a <i>mapping</i>:
|
|
<pre> a = '%<b>(lang)</b>s has %<b>(c)</b>03d quote types.' % {'c':2, 'lang':'Python}</pre>
|
|
(<i>vars()</i> function very handy to use on right-hand-side.)
|
|
<h3>
|
|
<font color="#000000">File Objects</font></h3>
|
|
Created with built-in function <i>open()</i>; may be created by other modules's
|
|
functions as well.
|
|
<h4>
|
|
Operators on file objects</h4>
|
|
|
|
<pre> f.<b>close</b>() close file f.
|
|
f.<b>fileno</b>() get fileno (fd) for f.
|
|
f.<b>flush</b>() flush file's internal buffer.
|
|
f.<b>isatty</b>() 1 if file is connected to a tty-like dev, else 0
|
|
f.<b>read</b>([size]) read at most <i>size</i> bytes from file and return
|
|
as a string object. If <i>size</i> omitted, read to EOF.
|
|
|
|
f.<b>readline</b>() read one entire line from file
|
|
f.<b>readlines</b>() read until EOF with readline() and return list
|
|
of lines read.
|
|
|
|
f.<b>seek</b>(offset, whence=0) set file's position, like
|
|
"stdio's fseek()".
|
|
whence == 0 then use absolute indexing
|
|
whence == 1 then offset relative to current pos
|
|
whence == 2 then offset relative to file end
|
|
|
|
f.<b>tell</b>() return file's current position
|
|
f.<b>write</b>(str) Write string to file.
|
|
f.<b>writelines</b>(list) Write list of strings to file.</pre>
|
|
|
|
<h4>
|
|
File Exceptions</h4>
|
|
|
|
<dl>
|
|
<dt>
|
|
EOFError</dt>
|
|
|
|
<dd>
|
|
End-of-file hit when reading (may be raised many times, e.g. if <i>f</i>
|
|
is a tty).</dd>
|
|
|
|
<dt>
|
|
IOError</dt>
|
|
|
|
<dd>
|
|
Other I/O-related I/O operation failure</dd>
|
|
</dl>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="AdvTypes"></a>Advanced Types</h2>
|
|
<i>-See manuals for more details</i> -
|
|
<ul>
|
|
<li>
|
|
<i>Module</i> objects</li>
|
|
|
|
<li>
|
|
<i>Class</i> objects</li>
|
|
|
|
<li>
|
|
<i>Class instance</i> objects</li>
|
|
|
|
<li>
|
|
<i>Type</i> objects (see module: types)</li>
|
|
|
|
<li>
|
|
<i>File</i> objects (see above)</li>
|
|
|
|
<li>
|
|
<i>Slice</i> objects</li>
|
|
|
|
<li>
|
|
<i>XRange</i> objects</li>
|
|
|
|
<li>
|
|
Callable types:</li>
|
|
|
|
<ul>
|
|
<li>
|
|
User-defined (written in Python):</li>
|
|
|
|
<ul>
|
|
<li>
|
|
User-defined <i>Function</i> objects</li>
|
|
|
|
<li>
|
|
User-defined <i>Method</i> objects</li>
|
|
</ul>
|
|
|
|
<li>
|
|
Built-in (written in C):</li>
|
|
|
|
<ul>
|
|
<li>
|
|
Built-in <i>Function</i> objects</li>
|
|
|
|
<li>
|
|
Built-in <i>Method</i> objects</li>
|
|
</ul>
|
|
</ul>
|
|
|
|
<li>
|
|
Internal Types:</li>
|
|
|
|
<ul>
|
|
<li>
|
|
<i>Code</i> objects (byte-compile executable Python code: <i>bytecode</i>)</li>
|
|
|
|
<li>
|
|
<i>Frame</i> objects (execution frames)</li>
|
|
|
|
<li>
|
|
<i>Traceback</i> objects (stack trace of an exception)</li>
|
|
</ul>
|
|
</ul>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="Statements"></a>Statements</h2>
|
|
|
|
<pre><b>pass</b> -- Null statement
|
|
<b>=</b> -- Assignment operator. Can unpack tuples, lists, strings
|
|
first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
|
|
Tip: x,y = y,x swaps x and y.
|
|
<b>del</b> <name>[,<name>]* -- Unbind name(s) from object. Object will be indirectly
|
|
(and automatically) deleted only if no longer referenced.
|
|
<b>print</b> [<c1> [, <c2> ]* [,]
|
|
-- Writes to sys.stdout.
|
|
Puts spaces between arguments. Puts newline at end
|
|
unless statement ends with comma.
|
|
Print is not required when running interactively,
|
|
simply typing an expression will print its value,
|
|
unless the value is None.
|
|
<b>exec</b> <x> [in <globals> [,<locals>]]
|
|
-- Executes <x> in namespaces provided. Defaults
|
|
to current namespaces. <x> can be a string, file
|
|
object or a function object.
|
|
<b>f</b>(<value>,... [<id>=<value>])
|
|
-- Call function 'f' with parameters. Parameters can
|
|
be passed by name or be omitted if function
|
|
defines default values. E.g. for 'f' is defined as
|
|
"def f(p1=1, p2=2)"
|
|
"f()" <=> "f(1, 2)"
|
|
"f(10)" <=> "f(10, 2)"
|
|
"f(p2=99)" <=> "f(1, 99)"</pre>
|
|
|
|
<h3>
|
|
Control Flow</h3>
|
|
|
|
<pre><b>if</b> <condition<i>></i><b>:</b> <suite<i>>
|
|
</i>[<b>elif</b> <condition<i>></i><b>:</b> <suite<i>></i>]*
|
|
[<b>else:</b> <suite<i>></i>]
|
|
-- usual if/else_if/else statement
|
|
|
|
<b>while</b> <condition><b>:</b> <suite>
|
|
[<b>else:</b> <suite>]
|
|
-- usual while statement. "else" suite is executed
|
|
after loop exits, unless the loop is exited with
|
|
"break"
|
|
|
|
<b>for</b> <target> <b>in</b> <condition-list><b>:</b> <suite>
|
|
[<b>else:</b> <suite>]
|
|
-- iterates over sequence "<condition-list>",
|
|
assigning each element to "<target>". Use built-in <i>range
|
|
</i> function to iterate a number of times.
|
|
"else" suite executed at end unless loop exited
|
|
with "break"
|
|
|
|
<b>break</b> -- immediately exit "for" or "while" loop
|
|
|
|
<b>continue</b> -- immediately do next iteration of "for" or "while" loop
|
|
|
|
<b>return</b> [<result>]
|
|
-- return from function (or method) and return
|
|
"<result>". If no result given, then returns <i>None</i>.</pre>
|
|
|
|
<h3>
|
|
Exception Statements</h3>
|
|
|
|
<pre><b>assert</b> expr[, message]
|
|
-- expr is evaluated. if false, raise exception AssertionError
|
|
with message. Inhibited if __debug__ is 0.</pre>
|
|
|
|
<pre><b>try:</b> <suite1>
|
|
[<b>except</b> [<exception> [, <value>]<b>:</b> <suite2>]+
|
|
[<b>else:</b> <suite3>]
|
|
-- statements in <suite1> are executed. If an
|
|
exception occurs, look in "except" clauses for
|
|
matching <exception>. If matches or bare "except"
|
|
execute suite of that clause. If no exception happens
|
|
suite in "else" clause is executed after <suite1>.
|
|
If <exception> has a value, it is put in <value>.
|
|
<exception> can also be tuple of exceptions, e.g.
|
|
"except (KeyError, NameError), val: print val"
|
|
|
|
<b>try:</b> <suite1>
|
|
<b>finally:</b> <suite2>
|
|
-- statements in <suite1> are executed. If no
|
|
exception, execute <suite2> (even if <suite1> is
|
|
exited with a "return", "break" or "continue"
|
|
statement). If exception did occur, executes
|
|
<suite2> and them immediately reraises exception.
|
|
|
|
<b>raise</b> <exception> [,<value> [,<traceback>]]
|
|
-- raises <exception> with optional value
|
|
<value>. Parameter <traceback>
|
|
specifies a traceback object to use when printing
|
|
the exception's backtrace.
|
|
<b>raise</b> -- a raise statement without arguments re-raises
|
|
the last exception raised in the current function
|
|
|
|
An exception is either a <i>string</i> (object) or a <i>class instance</i>.
|
|
Can create a new one simply by creating a new string:
|
|
|
|
my_exception = 'You did something wrong'
|
|
<b>try</b>:
|
|
if bad:
|
|
<b>raise</b> my_exception, bad
|
|
<b>except</b> my_exception, value:
|
|
print 'Oops', value</pre>
|
|
|
|
<pre>Exception classes must be derived from the predefined class: Exception, eg:</pre>
|
|
|
|
<pre> class text_exception(Exception):
|
|
<b>try</b>:
|
|
if bad:
|
|
<b>raise</b> text_exception()
|
|
# This is a shorthand for the form
|
|
# "raise <class>, <instance>"
|
|
<b>except</b> Exception:
|
|
print 'Oops'
|
|
# This will be printed because
|
|
# text_exception is a subclass of Exception
|
|
|
|
When an error message is printed for an unhandled exception which is a
|
|
class, the class name is printed, then a colon and a space, and
|
|
finally the instance converted to a string using the built-in function
|
|
str().</pre>
|
|
|
|
<pre>All built-in exception classes derives from StandardError, itself
|
|
derived from Exception.</pre>
|
|
|
|
<h3>
|
|
Name Space Statements</h3>
|
|
[1.51: On Mac & Windows, the case of module file names must now match
|
|
the case as used
|
|
<br> in the <i>import</i> statement]
|
|
<pre><i>Packages</i> (>1.5): a package is a name space which maps to a directory including
|
|
module(s) and the special initialization module '__init__.py'
|
|
(possibly empty). Packages/dirs can be nested. You address a
|
|
module's symbol via '[package.[package...]module.symbol's.</pre>
|
|
|
|
<pre><b>import</b> <module_id1> [, <module_id2>]*
|
|
-- imports modules. Members of module must be
|
|
referred to by qualifying with [package.]module name:
|
|
"import sys; print sys.argv:"
|
|
"import package1.subpackage.module; package1.subpackage.module.foo()"
|
|
|
|
<b>from</b> <module_id> <b>import</b> <id1> [, <id2>]*
|
|
-- imports names from module <module_id>. Names
|
|
are not qualified:
|
|
"from sys import argv; print argv"
|
|
"from package1 import module; module.foo()"
|
|
"from package1.module import foo; foo()"
|
|
|
|
<b>from</b> <module_id> <b>import *
|
|
</b> -- imports all names in module <module_id>, except
|
|
those starting with "_"; *to be used sparsely* :
|
|
"from sys import *; print argv"
|
|
"from package.module import *; print x'
|
|
|
|
<b>global</b> <id1> [,<id2>]*
|
|
-- ids are from global scope (usually meaning from module)
|
|
rather than local (usually meaning only in function).
|
|
-- E.g. in fct without "global" statements, assuming
|
|
"a" is name that hasn't been used in fct or module
|
|
so far:
|
|
-Try to read from "a" -> NameError
|
|
-Try to write to "a" -> creates "a" local to fcn
|
|
-If "a" not defined in fct, but is in module, then
|
|
-Try to read from "a", gets value from module
|
|
-Try to write to "a", creates "a" local to fct
|
|
|
|
But note "a[0]=3" starts with search for "a",
|
|
will use to global "a" if no local "a".</pre>
|
|
|
|
<h3>
|
|
Function Definition</h3>
|
|
|
|
<pre><b>def</b> <func_id> ([<param_list>])<b>:</b> <suite>
|
|
-- creates a function object and assigns it name
|
|
<func_id>.
|
|
|
|
<param_list> ==> [<id> [, <id>]*] [<id> =
|
|
<v> [,
|
|
<id> =
|
|
<v>]*]
|
|
[*<id>]
|
|
[**<id>]
|
|
[Args are passed by <b>value</b>.Thus only args representing a <i>mutable</i> object
|
|
can be modified (are <i>inout</i> parameters). Use a <b>tuple</b> to return more than
|
|
one value]</pre>
|
|
|
|
<pre>E.g.
|
|
<b>def</b> test (p1, p2 = 1+1, *rest, **keywords):
|
|
-- Parameters with "=" have default value (<v> is
|
|
evaluated when function defined).
|
|
If list has "*<id>" then <id> is assigned
|
|
a tuple of all remaining args passed to function.
|
|
(allows vararg functions).
|
|
If list has "**<id>" then <id> is assigned
|
|
a dictionary of all arguments passed as keywords.</pre>
|
|
|
|
<h3>
|
|
Class Definition</h3>
|
|
|
|
<pre><b>class</b> <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
|
|
-- Creates a class object and assigns it name <class_id>
|
|
<suite> may contain local "defs" of class methods and
|
|
assignments to class attributes.
|
|
E.g.
|
|
<b>class</b> my_class (class1, class_list[3]): ...
|
|
Creates a class object inheriting from both "class1" and whatever
|
|
class object "class_list[3]" evaluates to. Assigns new
|
|
class object to name "my_class".
|
|
|
|
-First arg to class methods is always instance object, called '<b>self</b>'
|
|
by convention.
|
|
-Special method <b>__init__</b>() is called when instance is created.
|
|
-Special method <b>__del__</b>() called when no more reference to object.
|
|
-Create instance by "<i>calling</i>" class object, possibly with arg
|
|
(thus instance=apply(aClassObject, args...) creates an instance!)
|
|
-In current implementation, can't subclass off built-in
|
|
classes. But can "wrap" them, see __getattr__() below.
|
|
|
|
|
|
E.g.
|
|
class c (c_parent):
|
|
def __init__(self, name): self.name = name
|
|
def print_name(self): print "I'm", self.name
|
|
def call_parent(self): c_parent.print_name(self)
|
|
|
|
instance = c('tom')
|
|
print instance.name
|
|
'tom'
|
|
instance.print_name()
|
|
"I'm tom"
|
|
|
|
Call parent's super class by accessing parent's method
|
|
directly and passing "self" explicitly (see "call_parent"
|
|
in example above).
|
|
|
|
Many other special methods available for implementing
|
|
arithmetic operators, sequence, mapping indexing, etc.</pre>
|
|
|
|
<h4>
|
|
Documentation Strings</h4>
|
|
Modules, classes and functions may be documented by placing a string literal
|
|
by itself as the first statement in the suite. The documentation can be
|
|
retrieved by getting the '<b>__doc__</b>' attribute from the module, class
|
|
or function.
|
|
<pre>Example:
|
|
class c:
|
|
"A description of 'c'"
|
|
def __init__(self):
|
|
"A description of the constructor"
|
|
# etc.
|
|
Then c.__doc__ <=> "A description of 'c'".
|
|
Then c.__init__.__doc__ <=> "A description of the constructor".</pre>
|
|
|
|
<h3>
|
|
Others</h3>
|
|
|
|
<pre><b>lambda</b> [<param_list>]: <returnedExpr>
|
|
-- Create an anonymous function. <returnedExpr> must be
|
|
an expression, not a statement (e.g., not "if xx:...",
|
|
"print xxx", etc.) and thus can't contain newlines.
|
|
Used mostly for filter(), map(), reduce() functions.</pre>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="BuiltIn"></a>Built-In Functions</h2>
|
|
|
|
<pre><b>__import__</b>(name[, globals[, locals[, fromlist]]])
|
|
Import module within the given context (see lib ref for more details)
|
|
|
|
<b>abs</b>(x) Return the absolute value of a number
|
|
|
|
<b>apply</b>(f, args[, keywords])
|
|
Call func/method <f> with args <args> and optional keywords
|
|
|
|
<b>callable</b>(x) Returns 1 if x callable, else 0.
|
|
|
|
<b>chr</b>(i) Return one-character string whose ASCII code is
|
|
integer i
|
|
|
|
<b>cmp</b>(x,y) Return neg, zero, pos if x <, ==, > to y
|
|
|
|
<b>coerce</b>(x,y) Return a tuple of the two <i>numeric</i> arguments converted to
|
|
a common type.
|
|
|
|
<b>compile</b>(string, filename, kind)
|
|
Compile <string> into a code object.
|
|
<filename> is used in error message, can be any string. It is
|
|
usually the file from which the code was read, or eg. '<string>'
|
|
if not read from file.
|
|
<kind> can be 'eval' if <string> is a single stmt, or 'single'
|
|
which prints the output of expression statements that
|
|
evaluate to something else than "None" or be 'exec'.
|
|
|
|
<b>complex</b>(real[, image])
|
|
Build a complex object (can also be done using J or j suffix,
|
|
e.g. 1+3J)</pre>
|
|
|
|
<pre><b>delattr</b>(obj, name)
|
|
deletes attribute named <name> of object <obj> <=> del obj.name</pre>
|
|
|
|
<pre><b>dir</b>([object]) If no args, return the list of names in current local
|
|
symbol table. With a module, class or class instance
|
|
object as arg, return list of names in its attr dict.
|
|
|
|
<b>divmod</b>(a,b) Returns tuple of (a/b, a%b)
|
|
|
|
<b>eval</b>(s, globals, locals)
|
|
Eval string <s> in (optional) <globals>, <locals>.
|
|
<s> must have no NULL's or newlines. <s> can also be a
|
|
code object.
|
|
|
|
E.g.: x = 1; incr_x = eval('x + 1')
|
|
|
|
<b>execfile</b>(file[, globals[, locals]])
|
|
Execute a file without creating a new module, unlike import.</pre>
|
|
|
|
<pre><b>filter</b>(function, sequence)
|
|
Construct a list from those elements of <sequence> for which
|
|
<function> returns true. <function> takes one parameter.
|
|
|
|
<b>float</b>(x) Convert a number or a string to floating point.
|
|
|
|
<b>getattr</b>(object, name[, default])) <font size=-1>[<default> arg added in 1.5.2]
|
|
</font> Get attr called <name> from <object>, e.g. getattr(x, 'f') <=> x.f).
|
|
If not found, raise AttributeError or return <default> if specified.
|
|
|
|
<b>globals</b>() Returns a dictionary containing current global variables.
|
|
|
|
<b>hasattr</b>(object, name)
|
|
Returns true if <object> has attr called <name>.
|
|
|
|
<b>hash</b>(object) Return the hash value of the object (if it has one)
|
|
|
|
<b>hex</b>(x) Convert a number to a hexadecimal string.
|
|
|
|
<b>id</b>(object) Return a unique 'identity' integer for an object.
|
|
|
|
<b>input</b>([prompt]) Prints prompt, if given. Reads input and evaluates it.</pre>
|
|
|
|
<pre><b>int</b>(x) Convert a number or a string to a plain integer.
|
|
|
|
<b>intern</b>(aString)
|
|
Enter <String> in the table of "interned strings" and
|
|
return the string. Interned strings are 'immortals'.
|
|
<b>isinstance</b>(obj, class)
|
|
return true if <obj> is an instance of <class></pre>
|
|
|
|
<pre><b>issubclass</b>(class1, class2)
|
|
return true if <class1> is derived from <class2></pre>
|
|
|
|
<pre><b>len</b>(s) Return the length (the number of items) of an object
|
|
(sequence or dictionary).
|
|
|
|
<b>list</b>(sequence)
|
|
Convert <sequence> into a list. If already a list,
|
|
return a copy of it.</pre>
|
|
|
|
<pre><b>locals</b>() Return a dictionary containing current local variables.
|
|
|
|
<b>long</b>(x) Convert a number or a string to a long integer.
|
|
|
|
<b>map</b>(function, list, ...)
|
|
Apply <function> to every item of <list> and return a list
|
|
of the results. If additional arguments are passed,
|
|
<function> must take that many arguments and it is given
|
|
to <function> on each call.
|
|
|
|
<b>max</b>(s) Return the largest item of a non-empty sequence.
|
|
|
|
<b>min</b>(s) Return the smallest item of a non-empty sequence.
|
|
|
|
<b>oct</b>(x) Convert a number to an octal string.
|
|
|
|
<b>open</b>(filename [, mode='r', [bufsize=<implementation dependent>]])
|
|
Return a new file object. First two args are same as
|
|
those for C's "stdio open" function. <bufsize> is 0
|
|
for unbuffered, 1 for line-buffered, negative for
|
|
sys-default, all else, of (about) given size.
|
|
|
|
<b>ord</b>(c) Return integer ASCII value of <c> (str of len 1).
|
|
|
|
<b>pow</b>(x, y [, z]) Return x to power y [modulo z]. See also ** operator.
|
|
|
|
<b>range</b>(start [,end [, step]])
|
|
return list of ints from >= start and < end.
|
|
With 1 arg, list from 0..<arg>-1
|
|
With 2 args, list from <start>..<end>-1
|
|
With 3 args, list from <start> up to <end> by <step>
|
|
|
|
<b>raw_input</b>([prompt])
|
|
Print prompt if given, then read string from std
|
|
input (no trailing \n).
|
|
|
|
<b>reduce</b>(f, list [, init])
|
|
Apply the binary function <f> to the items of
|
|
<list> so as to reduce the list to a single value.
|
|
If <init> given, it is "prepended" to <list>.
|
|
|
|
<b>reload</b>(module) Re-parse and re-initialize an already imported module.
|
|
Useful in interactive mode, if you want to reload a
|
|
module after fixing it. If module was synactically
|
|
correct but had an error in initialization, must
|
|
import it one more time before calling reload().
|
|
|
|
<b>repr</b>(object) Return a string containing a printable representation
|
|
of an object. Equivalent to `object` (using
|
|
backquotes).
|
|
|
|
<b>round</b>(x,n=0) Return the floating point value x rounded to n digits
|
|
after the decimal point.
|
|
|
|
<b>setattr</b>(object, name, value)
|
|
This is the counterpart of getattr().
|
|
setattr(o, 'foobar', 3) <=> o.foobar = 3
|
|
<u>Create</u> attribute if it doesn't exist!
|
|
|
|
<b>slice</b>([start,] stop[, step])
|
|
Return a <i>slice object</i> representing a range, with R/O
|
|
attributes: start, stop, step.</pre>
|
|
|
|
<pre><b>str</b>(object) Return a string containing a nicely printable
|
|
representation of an object.
|
|
|
|
<b>tuple</b>(sequence) Creates a tuple with same elements as <sequence>. If
|
|
already a tuple, return itself (not a copy).
|
|
|
|
<b>type</b>(obj) Return a type object [see module <i>types</i>]representing the
|
|
type of <obj>. E.g., import types
|
|
if type(x) == types.StringType: print 'It is a string'
|
|
|
|
<b>vars</b>([object]) Without arguments, return a dictionary corresponding
|
|
to the current local symbol table. With a module,
|
|
class or class instance object as argument
|
|
returns a dictionary corresponding to the object's
|
|
symbol table. Useful with "%" formatting operator.
|
|
|
|
<b>xrange</b>(start [, end [, step]])
|
|
Like range(), but doesn't actually store entire list
|
|
all at once. Good to use in "for" loops when there is a
|
|
big range and little memory.</pre>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="BuiltInExc"></a>Built-In Exceptions</h2>
|
|
|
|
<dl>
|
|
<dt>
|
|
<i>Exception</i></dt>
|
|
|
|
<dt>
|
|
Root class for all exceptions</dt>
|
|
|
|
<dt>
|
|
<i> SystemExit</i></dt>
|
|
|
|
<dt>
|
|
On 'sys.exit()'</dt>
|
|
|
|
<dt>
|
|
<i> StandardError</i></dt>
|
|
|
|
<dt>
|
|
|
|
Base class for all built-in exceptions; derived from Exception root class.</dt>
|
|
|
|
<dt>
|
|
<i> ArithmeticError</i></dt>
|
|
|
|
<dt>
|
|
|
|
Base class for OverflowError, ZeroDivisionError, FloatingPointError</dt>
|
|
|
|
<dt>
|
|
<i> OverflowError</i></dt>
|
|
|
|
<br>
|
|
On excessively large arithmetic operation
|
|
<dt>
|
|
<i> ZeroDivisionError</i></dt>
|
|
|
|
<dd>
|
|
On division or modulo
|
|
operation with 0 as 2nd arg</dd>
|
|
|
|
<dt>
|
|
<i> FloatingPointError</i></dt>
|
|
|
|
<dt>
|
|
|
|
when a floating point operation fails.</dt>
|
|
|
|
<dt>
|
|
<i> </i></dt>
|
|
|
|
<br><i> AssertionError</i>
|
|
<dt>
|
|
|
|
When an <i>assert</i> statement fails.</dt>
|
|
|
|
<dt>
|
|
<i> AttributeError</i></dt>
|
|
|
|
<br>
|
|
On attribute reference or assignment failure
|
|
<dt>
|
|
<i> EOFError</i></dt>
|
|
|
|
<br>
|
|
Immediate end-of-file hit by input() or raw_input()
|
|
<dt>
|
|
<i> EnvironmentError</i><font size=-1>
|
|
[<b>new</b> in 1.5.2]</font></dt>
|
|
|
|
<dt>
|
|
|
|
On error outside Python; error arg tuple is (errno, errMsg...)</dt>
|
|
|
|
<dt>
|
|
<i> IOError</i><font size=-1>
|
|
[<b>changed</b> in 1.5.2]</font></dt>
|
|
|
|
<dd>
|
|
I/O-related operation failure</dd>
|
|
|
|
<dt>
|
|
<i> OSError</i><font size=-1>
|
|
[<b>new</b> in 1.5.2]</font></dt>
|
|
|
|
<dd>
|
|
used by the <i>os</i> module's <i>os.error</i>
|
|
exception.</dd>
|
|
|
|
<dt>
|
|
<i> ImportError</i></dt>
|
|
|
|
<dd>
|
|
On failure of `import' to find module or name</dd>
|
|
|
|
<dt>
|
|
<i> KeyboardInterrupt</i></dt>
|
|
|
|
<dd>
|
|
On user entry of the interrupt key (often `Control-C')</dd>
|
|
|
|
<dt>
|
|
<i> LookupError</i></dt>
|
|
|
|
<dt>
|
|
|
|
base class for IndexError, KeyError</dt>
|
|
|
|
<dt>
|
|
<i> IndexError</i></dt>
|
|
|
|
<dd>
|
|
On out-of-range sequence
|
|
subscript</dd>
|
|
|
|
<dt>
|
|
<i> KeyError</i></dt>
|
|
|
|
<dd>
|
|
On reference to a non-existent
|
|
mapping (dict) key</dd>
|
|
|
|
<dt>
|
|
<i> MemoryError</i></dt>
|
|
|
|
<dd>
|
|
On recoverable memory exhaustion</dd>
|
|
|
|
<dt>
|
|
<i> NameError</i></dt>
|
|
|
|
<dd>
|
|
On failure to find a local or global (unqualified)
|
|
name</dd>
|
|
|
|
<dt>
|
|
<i> RuntimeError</i></dt>
|
|
|
|
<dd>
|
|
Obsolete catch-all; define a suitable error instead</dd>
|
|
|
|
<br> <i>NotImplementedError</i><font size=-1>
|
|
[<b>new</b> in 1.5.2]</font>
|
|
<dd>
|
|
On method not implemented</dd>
|
|
|
|
<dt>
|
|
<i> SyntaxError</i></dt>
|
|
|
|
<dd>
|
|
On parser encountering a syntax error</dd>
|
|
|
|
<dt>
|
|
<i> SystemError</i></dt>
|
|
|
|
<dd>
|
|
On non-fatal interpreter error - bug - report
|
|
it</dd>
|
|
|
|
<dt>
|
|
<i> TypeError</i></dt>
|
|
|
|
<dd>
|
|
On passing inappropriate type to built-in op or
|
|
func</dd>
|
|
|
|
<dt>
|
|
<i> ValueError</i></dt>
|
|
|
|
<dd>
|
|
On arg error not covered by TypeError or more
|
|
precise</dd>
|
|
</dl>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="SpecialMethods"></a>Standard methods & operators redefinition
|
|
in classes</h2>
|
|
|
|
<pre>Standard methods & operators map to methods in user-defined classes and thus may be redefined, e.g.
|
|
class x:
|
|
def __init__(self, v): self.value = v
|
|
def __add__(self, r): return self.value + r
|
|
a = x(3) # sort of like calling x.__init__(a, 3)
|
|
a + 4 # is equivalent to a.__add__(4)</pre>
|
|
|
|
<h3>
|
|
Special methods for any class</h3>
|
|
(s: self, o: other)
|
|
<pre> __init__(s, args) object instantiation
|
|
|
|
__del__(s) called on object demise (refcount becomes 0)
|
|
__repr__(s) repr() and `...` conversions
|
|
__str__(s) str() and 'print' statement
|
|
__cmp__(s, o) implements <, ==, >, <=, <>, !=, >=, is [not]
|
|
__hash__(s) hash() and dictionary operations
|
|
__getattr__(s, name) called when attr lookup doesn't find <name>
|
|
__setattr__(s, name, val) called when setting an attr
|
|
(inside, don't use "self.name = value"
|
|
use "self.__dict__[name] = val")
|
|
__delattr__(s, name) called to delete attr <name>
|
|
|
|
__call__(self, *args) called when an instance is called as function.</pre>
|
|
|
|
<h3>
|
|
Operators</h3>
|
|
|
|
<blockquote>See list in the <i>operator</i> module. Operator function names
|
|
are provided with 2 variants, with or without
|
|
<br>ading & trailing '__' (eg. __add__ or add).
|
|
<p><b>Numeric operations special methods</b>
|
|
<br>(s: self, o: other)</blockquote>
|
|
|
|
<pre> s+o = __add__(s,o) s-o = __sub__(s,o)
|
|
s*o = __mul__(s,o) s/o = __div__(s,o)
|
|
s%o = __mod__(s,o) divmod(s,o) = __divmod__(s,o)
|
|
pow(s,o) = __pow__(s,o)
|
|
s&o = __and__(s,o)
|
|
s^o = __xor__(s,o) s|o = __or__(s,o)
|
|
s<<o = __lshift__(s,o) s>>o = __rshift__(s,o)
|
|
nonzero(s) = __nonzero__(s) (used in boolean testing)
|
|
-s = __neg__(s) +s = __pos__(s)
|
|
abs(s) = __abs__(s) ~s = __invert__(s) (bitwise)
|
|
int(s) = __int__(s) long(s) = __long__(s)
|
|
float(s) = __float__(s)
|
|
oct(s) = __oct__(s) hex(s) = __hex__(s)
|
|
coerce(s,o) = __coerce__(s,o)
|
|
|
|
Right-hand-side equivalents for all binary operators exist;
|
|
are called when class instance is on r-h-s of operator:
|
|
a + 3 calls __add__(a, 3)
|
|
3 + a calls __radd__(a, 3)</pre>
|
|
|
|
<blockquote><b>All seqs and maps, general operations plus:</b>
|
|
<br>(s: self, i: index or key)</blockquote>
|
|
|
|
<pre> len(s) = __len__(s) length of object, >= 0. Length 0 == false
|
|
s[i] = __getitem__(s,i) Element at index/key i, origin 0</pre>
|
|
|
|
<blockquote><b>Sequences, general methods, plus:</b>
|
|
<pre> s[i]=v = __setitem__(s,i,v)
|
|
del s[i] = __delitem__(s,i)
|
|
s[i:j] = __getslice__(s,i,j)
|
|
s[i:j]=seq = __setslice__(s,i,j,seq)
|
|
del s[i:j] = __delslice__(s,i,j) == s[i:j] = []
|
|
seq * n = __repeat__(seq, n)
|
|
s1 + s2 = __concat__(s1, s2)</pre>
|
|
<b>Mappings, general methods, plus</b>
|
|
<pre> hash(s) = __hash__(s) - hash value for dictionary references
|
|
s[k]=v = __setitem__(s,k,v)
|
|
del s[k] = __delitem__(s,k)</pre>
|
|
</blockquote>
|
|
|
|
<h2>
|
|
<a NAME="typeAttributes"></a>Special informative state attributes for some
|
|
types:</h2>
|
|
|
|
<pre> <b>Lists & Dictionaries</b>:
|
|
__methods__ (list, R/O): list of method names of the object
|
|
|
|
<b>Modules</b>:
|
|
__dict__ (dict, R/O): module's name space
|
|
__doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
|
|
__name__(string, R/O): module name (also in __dict__['__name__'])
|
|
__file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
|
|
modules statically linked to the interpreter)
|
|
<b>Classes</b>: [bold: writable since 1.5.2]
|
|
__bases__ (tuple, R/<b>W)</b>: parent classes
|
|
__dict__ (dict, R/<b>W</b>): attributes (class name space)
|
|
__name__(string, R/<b>W</b>): class name (also in __dict__['__name__'])
|
|
__doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
|
|
|
|
<b>Instances:
|
|
</b> __class__ (class, R/W): instance's class
|
|
__dict__ (dict, R/W): attributes
|
|
|
|
|
|
<b>User-defined functions</b>: [bold: writable since 1.5.2]
|
|
__doc__ (string/None, R/<b>W</b>): doc string
|
|
__name__(string, R/O): function name
|
|
func_defaults (tuple/None, R/<b>W</b>): default args values if any
|
|
func_code (code, R/<b>W</b>): code object representing the compiled function body
|
|
func_globals (dict, R/O): ref to dictionary of func global variables
|
|
func_doc (R/<b>W</b>): same as __doc__
|
|
|
|
<b>User-defined Methods</b>:
|
|
im_self (instance/None, R/O): target instance object (None if unbound)
|
|
im_func (function, R/O): function object
|
|
im_class (class, R/O): class defining the method (may be a base class)
|
|
__doc__ (string/None, R/O): doc string
|
|
__name__(string, R/O): method name (same as im_func.__name__)
|
|
|
|
<b>Built-in Functions & methods</b>:
|
|
__doc__ (string/None, R/O): doc string
|
|
__name__ (string, R/O): function name
|
|
__self__ : [methods only] target object
|
|
__members__ = list of attr names: ['__doc__','__name__','__self__'])
|
|
|
|
<b>Codes</b>:
|
|
co_argcount (int, R/0): number of positional args
|
|
co_nlocals (int, R/O): number of local vars (including args)
|
|
co_varnames (tuple, R/O): names of local vars (starting with args)
|
|
co_code (string, R/O): sequence of bytecode instructions
|
|
co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
|
|
fct doc (or None)
|
|
co_name (string, R/O): name of function
|
|
co_names (tuple, R/O): names used by the bytecode
|
|
co_filename (string, R/O): filename from which the code was compiled
|
|
co_flags (int, R/O): flags for the interpreter
|
|
bit 2 set if fct uses "*arg" syntax
|
|
bit 3 set if fct uses '**keywords' syntax
|
|
HINT: use codehack.getlineno() to get 1st lineNo of a code object
|
|
|
|
<b>Frames</b>:
|
|
f_back (frame/None, R/O): previous stack frame (towards the caller)
|
|
f_code (code, R/O): code object being executed in this frame
|
|
f_locals (dict, R/O): local vars
|
|
f_globals (dict, R/O): global vars
|
|
f_builtins (dict, R/O): built-in (intrinsic) names
|
|
f_restricted (int, R/O): flag indicating whether fct is executed in
|
|
restricted mode
|
|
f_lineno (int, R/O): current line number
|
|
f_lasti (int, R/O): precise instruction (index into bytecode)
|
|
f_trace (function/None, R/W): debug hook called at start of each source line
|
|
|
|
<b>Tracebacks</b>:
|
|
tb_next (frame/None, R/O): next level in stack trace (towards the frame where
|
|
the exception occurred)
|
|
tb_frame (frame, R/O): execution frame of the current level
|
|
tb_lineno (int, R/O): line number where the exception occured
|
|
tb_lasti (int, R/O): precise instruction (index into bytecode)
|
|
|
|
<b>Slices</b>:
|
|
start (any/None, R/O): lowerbound
|
|
stop (any/None, R/O): upperbound
|
|
step (any/None, R/O): step value
|
|
|
|
<b>Complex numbers</b>:
|
|
real (float, R/O): real part
|
|
imag (float, R/O): imaginary part
|
|
|
|
<b> XRanges</b>:
|
|
tolist (Built-in method, R/O): ?</pre>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="ImportantModules"></a>Important Modules</h2>
|
|
|
|
<center><a NAME="sysModule"></a><b><i><font size=+2>sys</font></i></b></center>
|
|
<b>Some variables:</b>
|
|
<pre>argv -- The list of command line arguments passed to a
|
|
Python script. sys.argv[0] is the script name.
|
|
builtin_module_names
|
|
-- A list of strings giving the names of all modules
|
|
written in C that are linked into this interpreter.
|
|
|
|
check_interval -- How often to check for thread switches or signals
|
|
(measured in number of virtual machine instructions)
|
|
exc_type
|
|
exc_value
|
|
exc_traceback -- <b>Deprecated</b> since release 1.5. Use exc_info() instead.
|
|
|
|
exitfunc -- User can set to a parameterless fcn. It will get
|
|
called before interpreter exits.
|
|
last_type
|
|
last_value
|
|
last_traceback -- Set only when an exception not handled and
|
|
interpreter prints an error. Used by debuggers.
|
|
|
|
maxint -- maximum positive value for integers</pre>
|
|
|
|
<pre>modules -- Dictionary of modules that have already been loaded.
|
|
|
|
path -- Search path for external modules. Can be modified
|
|
by program.
|
|
platform -- The current platform, e.g. "sunos5", "win32"
|
|
ps1
|
|
ps2 -- prompts to use in interactive mode.
|
|
|
|
stdin
|
|
stdout
|
|
stderr -- File objects used for I/O. User can redirect by
|
|
assigning a new file object to them (or any object:
|
|
.with a method write(string) for stdout/stderr,
|
|
.with a method readline() for stdin)
|
|
|
|
version -- string containing version info about Python interpreter.
|
|
|
|
(and also: copyright, dllhandle, exec_prefix, prefix)</pre>
|
|
<b>Functions:</b>
|
|
<pre>exit(n) -- Exit with status <n>. Raises SystemExit exception.
|
|
(Hence can be caught and ignored by program)
|
|
getrefcount(object)
|
|
-- Return the reference count of the object. Generally 1 higher
|
|
than you might expect, because of <object> arg temp reference.
|
|
setcheckinterval(interval)
|
|
-- Set the interpreter's thread switching interval (in number of virtual
|
|
code instructions, default:10).
|
|
settrace(func) -- Sets a trace function: called before each line of
|
|
code is exited.
|
|
setprofile(func)
|
|
-- Sets a profile function for performance profiling.
|
|
exc_info() -- info on exception currently being handled; this is a
|
|
tuple (exc_type, exc_value, exc_traceback).
|
|
<b>Warning</b>: assigning the traceback return value to a local
|
|
variable in a function handling an exception will cause
|
|
a circular reference.</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="osModule"></a><b><i><font size=+2>os</font></i></b></center>
|
|
"synonym" for whatever O/S-specific module is proper for current environment.
|
|
Uses "posix" whenever possible.
|
|
<p><b>Variables</b>
|
|
<br>name -- name
|
|
of O/S-specific module (e.g. "posix", "mac", "nt")
|
|
<br>path
|
|
-- O/S-specific module for path manipulations.
|
|
<br>
|
|
on Unix, os.path.split() <=> posixpath.split()
|
|
<br>curdir -- string used
|
|
to represent current directory ('.')
|
|
<br>pardir -- string used
|
|
to represent parent directory ('..')
|
|
<br>sep
|
|
-- string used to separate directories ('/' or '\')
|
|
<br>pathsep -- character used to separate
|
|
search path components (as in $PATH), eg. ';' for windows.
|
|
<br>linesep -- [1.5.2] line separator
|
|
as used in <b>binary</b> files, ie '\n' on Unix, '\r\n' on Dos/Win, '\r'
|
|
on Mac
|
|
<p><b>Functions</b>
|
|
<br>makedirs(path[, mode=0777])<font size=-1>
|
|
[<b>new</b> in 1.5.2]</font>
|
|
<br>
|
|
-- Recursive directory creation (create required intermediary dirs); os.error
|
|
if fails.
|
|
<br>removedirs(path)<font size=-1>
|
|
[<b>new</b> in 1.5.2]</font>
|
|
<br>
|
|
-- Recursive directory creation (create required intermediary dirs); os.error
|
|
if fails.
|
|
<br>renames(old, new)<font size=-1>
|
|
[<b>new</b> in 1.5.2]</font>
|
|
<br>
|
|
-- Recursive directory or file renaming; os.error if fails.
|
|
<p>
|
|
<hr>
|
|
<center><a NAME="posixModule"></a><b><i><font size=+2>posix</font></i></b></center>
|
|
don't import this module directly, import <i>os</i> instead !
|
|
<p><b>Variables:</b>
|
|
<pre>environ -- dictionary of environment variables, e.g.
|
|
posix.environ['HOME']. [Windows: before release 1.52 case is significant; from 1.52,
|
|
os.environ is all uppercase but accesses are case insensitive]
|
|
|
|
error -- exception raised on POSIX-related error.
|
|
Corresponding value is tuple of errno code and
|
|
perror() string.</pre>
|
|
<b>Some Functions (see doc for more):</b>
|
|
<pre>chdir(path) -- change current directory to <path>.
|
|
chmod(path, mode)
|
|
-- change the mode of <path> to the numeric <mode>
|
|
close(fd) -- Close file descriptor <fd> opened with posix.open.
|
|
_exit(n) -- Immediate exit, with no cleanups, no SystemExit,
|
|
etc. Should use this to exit a child process.
|
|
execv(p, args) -- "Become" executable <p> with args <args>
|
|
getcwd() -- return a string representing the current working directory
|
|
getpid() -- return the current process id
|
|
fork() -- Like C's fork(). Returns 0 to child, child pid to parent.
|
|
[Not on Windows]
|
|
kill(pid, signal)
|
|
-- Like C's kill [Not on Windows]
|
|
listdir(path) -- List names of entries in directory <path>.
|
|
lseek(fd, pos, how)
|
|
-- set current position in file <fd> to position <pos>, expressed
|
|
as an offset relative to beginning of file (how=0), to
|
|
current position (how=1), or to end of file (how=2)
|
|
mkdir(path[, mode])
|
|
-- Creates a directory named <path> with numeric <mode>
|
|
(default 0777)
|
|
open(file, flags, mode)
|
|
-- Like C's open(). Returns file descriptor. Use file object fcts
|
|
rather than this low level ones.
|
|
pipe() -- Creates pipe. Returns pair of file descriptors (r, w) [Not on Windows].
|
|
popen(command, mode='r', buffSize=0)
|
|
-- Open a pipe to or from <command>. Result is a file
|
|
object to read to or write from, as indicated by
|
|
<mode> being 'r' or 'w'.
|
|
remove(path) -- see unlink.
|
|
rename(src, dst)-- Rename/move the file or directory <src> to <dst>. [error if
|
|
target name already exists]
|
|
rmdir(path) -- Remove the directory <path>
|
|
read(fd, n) -- Read <n> bytes from <fd> and return as string.
|
|
stat(path) -- Returns st_mode, st_ino, st_dev, st_nlink, st_uid,
|
|
st_gid, st_size, st_atime, st_mtime, st_ctime.
|
|
[st_ino, st_uid, st_gid are dummy on Windows]
|
|
system(command) -- Execute string <command> in a subshell. Returns exit
|
|
status of subshell.
|
|
times() -- return accumulated CPU times in sec (user, system, children's user,
|
|
children's sys, elapsed real time). [3 last not on Windows]
|
|
unlink(path) -- Unlink ("delete") path/file. same as: remove
|
|
utime(path, (aTime, mTime))
|
|
-- Set the access & modified time of the file to the given tuple of values.
|
|
wait() -- Wait for child process completion. Returns tuple of
|
|
pid, exit_status [Not on Windows]
|
|
waitpid(pid, options)
|
|
-- Wait for process pid to complete. Returns tuple of
|
|
pid, exit_status [Not on Windows]
|
|
write(fd, str) -- Write <str> to <fd>. Returns num bytes written.</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="posixpathModule"></a><b><i><font size=+2>posixpath</font></i></b></center>
|
|
Do not import this module directly, import <i>os</i> instead and refer
|
|
to this module as os.path. (e.g. os.path.exists(p)) !
|
|
<p><b>Some Functions (see doc for more):</b>
|
|
<pre>exists(p) -- True if string <p> is an existing path
|
|
expanduser(p) -- Returns string that is (a copy of) <p> with "~" expansion done.
|
|
expandvars(p) -- Returns string that is (a copy of) <p> with environment vars expanded.
|
|
[Windows: case significant; Use Unix: <b>$</b>var notation,not %var%]
|
|
getsize(filename)<font size=-1> [<b>new</b> in 1.5.2]
|
|
</font> -- return the size in bytes of <filename>. raise os.error.
|
|
getmtime(filename) <font size=-1> [<b>new</b> in 1.5.2]
|
|
</font> -- return last modification time of <filename> (integer nb of seconds since epoch).
|
|
getatime(filename) <font size=-1> [<b>new</b> in 1.5.2]
|
|
</font> -- return last access time of <filename> (integer nb of seconds since epoch).
|
|
isabs(p) -- True if string <p> is an absolute path.
|
|
isdir(p) -- True if string <p> is a directory.
|
|
islink(p) -- True if string <p> is a symbolic link.
|
|
ismount(p) -- True if string <p> is a mount point [true for all dirs on Windows].
|
|
join(p[,q[,...]])
|
|
-- Joins one or more path components intelligently.
|
|
split(p) -- Splits into (head, tail) where <tail> is last
|
|
pathname component and <head> is everything leading
|
|
up to that. <=> (dirname(p), basename(p))
|
|
splitdrive(p) -- Splits path in a pair ('drive:', tail) [on Windows]
|
|
splitext(p) -- Splits into (root, ext) where last comp of <root>
|
|
contains no periods and <ext> is empty or starts
|
|
with a period.
|
|
walk(p, visit, arg)
|
|
-- Calls the function <visit> with arguments
|
|
(<arg>, <dirname>, <names>) for each directory recursively in
|
|
the directory tree rooted at <p> (including p itself if it's a dir)
|
|
The argument <dirname> specifies the visited directory, the argument
|
|
<names> lists the files in the directory. The <visit> function may
|
|
modify <names> to influence the set of directories visited below
|
|
<dirname>, e.g., to avoid visiting certain parts of the tree.
|
|
[1.52, NT version: samefile(), sameopenfile(), samestat() deprecated because not reliable]</pre>
|
|
|
|
<center>
|
|
<hr WIDTH="100%"><a NAME="timeModule"></a><b><i><font size=+2>time</font></i></b></center>
|
|
|
|
<p><b>Variables</b>
|
|
<pre>altzone -- signed offset of local DST timezone in sec west of the 0th meridian.
|
|
daylight -- nonzero if a DST timezone is specified</pre>
|
|
<b>Functions</b>
|
|
<pre>time() -- return a float representing UTC time in seconds since the epoch.
|
|
gmtime(secs), localtime(secs)
|
|
-- return a tuple representing time : (year aaaa, month(1-12),
|
|
day(1-31), hour(0-23), minute(0-59), second(0-59), weekday
|
|
(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1))
|
|
asctime(timeTuple),
|
|
strftime(format, timeTuple)
|
|
-- return a formated string representing time.
|
|
mktime(tuple) -- inverse of localtime(). Return a float.
|
|
strptime(string[, format]) <font size=-1> [<b>new</b> in 1.5.2]
|
|
</font> -- parse a formated string representing time, return tuple as in gmtime().
|
|
sleep(secs) -- Suspend execution for <secs> seconds. <secs> can be a float.</pre>
|
|
|
|
<pre>and also: clock, ctime.</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="stringModule"></a><b><i><font size=+2>string</font></i></b></center>
|
|
|
|
<p><b>Some Variables:</b>
|
|
<pre>digits -- The string '0123456789'
|
|
hexdigits, octdigits -- legal hexadecimal & octal digits
|
|
letters
|
|
uppercase
|
|
lowercase
|
|
whitespace
|
|
-- Strings containing the appropriate characters
|
|
index_error -- Exception raised by index() if substr not found.</pre>
|
|
|
|
<pre><b>Some Functions:</b>
|
|
expandtabs(s, tabSize) -- returns a copy of string <s> with tabs expanded.
|
|
find/rfind(s, sub[, start=0[, end=0])
|
|
-- Return the lowest/highest index in <s> where the substring
|
|
<sub> is found such that <sub> is wholly contained in
|
|
s[start:end]. Return -1 if <sub> not found.
|
|
ljust/rjust/center(s, width)
|
|
-- Return a copy of string <s> left/right justified/centerd in a
|
|
field of given width, padded with spaces. <s> is never
|
|
truncated.
|
|
lower/upper(s) -- Return a string that is (a copy of) <s> in lowercase/uppercase
|
|
split(s[, sep=whitespace[, maxsplit=0]])
|
|
-- Return a list containing the words of the string <s>,
|
|
using the string <sep> as a separator.
|
|
join(words[, sep=' ']) -- Concatenate a list or tuple of words with intervening
|
|
separators; inverse of split.
|
|
replace(s, old, new[, maxsplit=0]
|
|
-- Returns a copy of string <s> with all occurences of substring
|
|
<old> replaced by <new>. Limits to <maxsplit> first
|
|
substitutions if specified.
|
|
strip(s) -- Return a string that is (a copy of) <s> without leading
|
|
and trailing whitespace. see also lstrip, rstrip.</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="reModule"></a><b><i><font size=+2>re</font></i></b></center>
|
|
Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
|
|
litteralize backslashes.
|
|
<p><b>Regular Expression Syntax:</b>
|
|
<pre>. matches any character (including newline if DOTALL flag specified)
|
|
^ matches start of the string (of every line in MULTILINE mode)
|
|
$ matches end of the string (of every line in MULTILINE mode)
|
|
* 0 or more of preceding regular expression (as <b>many</b> as possible)
|
|
+ 1 or more of preceding regular expression (as <b>many</b> as possible)
|
|
? 0 or 1 occurence of preceding regular expression
|
|
*?, +?, ?? Same as *, + and ? but matches as <b>few</b> characters as possible
|
|
{m,n} matches from m to n repetitions of preceding RE
|
|
{m,n}? idem, attempting to match as <b>few</b> repetitions as possible
|
|
[ ] defines character set: e.g. '[a-zA-Z]' to match all letters
|
|
(see also \w \S)
|
|
[^ ] defines complemented character set: matches if char is NOT in set
|
|
\ escapes special chars '*?+&$|()' and introduces special sequences
|
|
(see below). Due to Python string rules, write as '\\' or
|
|
r'\' in the pattern string.
|
|
\\ matches a litteral '\'; due to Python string rules, write as '\\\\'
|
|
in pattern string, or better using raw string: r'\\'.
|
|
| specifies alternative: 'foo|bar' matches 'foo' or 'bar'
|
|
(...) matches any RE inside (), and delimits a <i>group</i>.
|
|
(?:...) idem but does'nt delimit a <i>group</i>.
|
|
(?=...) matches if ... matches next, but doesn't consume any of the string
|
|
e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by 'Asimov'.
|
|
(?!...) matches if ... <b>doesn't</b> match next. Negative of (?=...)
|
|
(?P<<i>name</i>>...) matches any RE inside (), and delimits a <b>named</b> <i>group</i>.
|
|
(e.g. r'(?P<id>[a-zA-Z_]\w*)' defines a group named <i>id</i>)
|
|
(?P=<i>name</i>) matches whatever text was matched by the earlier group named <i>name</i>.
|
|
(?#...) A comment; ignored.
|
|
(?<i>letter</i>) <i>letter</i> is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
|
|
(re.I, re.L, re.M, re.S, re.X) for the entire RE.</pre>
|
|
|
|
<pre> <u>SPECIAL SEQUENCES</u>:
|
|
\<i>number</i> matches content of the <i>group</i> of the same number; groups are numbered
|
|
starting from 1
|
|
\A matches only at the start of the string
|
|
\b empty str at beg or end of <i>word</i>: '\bis\b' matches 'is', but not 'his'
|
|
\B empty str NOT at beginning or end of word
|
|
\d any decimal digit (<=> [0-9])
|
|
\D any non-decimal digit char (<=> [^O-9])
|
|
\s any whitespace char (<=> [ \t\n\r\f\v])
|
|
\S any non-whitespace char (<=> [^ \t\n\r\f\v])
|
|
\w any alphaNumeric char (depends on LOCALE flag)
|
|
\W any non-alphaNumeric char (depends on LOCALE flag)
|
|
\Z matches only at the end of the string</pre>
|
|
<b>Variables:</b>
|
|
<pre>error -- Exception when pattern string isn't a valid regexp.</pre>
|
|
<b>Functions:</b>
|
|
<pre><a NAME="re.compile"></a>compile(pattern[, flags=0])
|
|
-- Compile a RE pattern string into a <i><a href="#regExpObj">regular expression object</a></i>.
|
|
Flags (combinable by |):
|
|
I or IGNORECASE or (?i): case insensitive matching
|
|
L or LOCALE or (?L): make \w, \W, \b, \B dependent on the
|
|
current locale
|
|
M or MULTILINE or (?m): matches every new line and not only
|
|
start/end of the whole string
|
|
S or DOTALL or (?s): '.' matches ALL chars, including newline
|
|
X or VERBOSE or (?x)</pre>
|
|
|
|
<pre>escape(string) -- return (a copy of) string with all non-alphanumerics backslashed.
|
|
match(pattern, string[, flags])
|
|
-- if 0 or more chars at <b>beginning</b> of <string> match the RE pattern string,
|
|
return a corresponding <i><a href="#matchObject">MatchObject</a></i> instance, or None if no match.
|
|
search(pattern, string[, flags])
|
|
--scan thru <string> for a location matching <pattern>, return a
|
|
corresponding <i><a href="#matchObject">MatchObject</a></i> instance, or None if no match.
|
|
split(pattern, string[, maxsplit=0])
|
|
--split <string> by occurrences of <pattern>. If capturing () are used in
|
|
pattern, then occurrences of patterns or subpatterns are also returned.
|
|
findall(pattern, string) [<b>new</b> in 1.5.2]
|
|
--return a list of non-overlapping matches in <pattern>, either a list of
|
|
groups or a list of tuples if the pattern has more than 1 group.
|
|
sub(pattern, repl, string[, count=0])
|
|
--return string obtained by replacing the (<count> first) lefmost non-
|
|
overlapping occurrences of <pattern> (a string or a RE object) in <string>
|
|
by <repl>; <repl> can be a string or a fct called with a single <i><a href="#matchObject">MatchObj
|
|
</a></i> arg, which must return the replacement string.
|
|
subn(pattern, repl, string[, count=0])
|
|
|
|
--same as sub(), but returns a tuple (newString, numberOfSubsMade)</pre>
|
|
<a NAME="regExpObj"></a><b>Regular Expression Objects</b>
|
|
<br>(RE objects are returned by the <a href="#re.compile">compile</a> fct)
|
|
<p><b>Attributes:</b>
|
|
<pre>flags -- flags arg used when RE obj was compiled, or 0 if none provided
|
|
groupindex -- dictionary of {group name: group number} in pattern
|
|
pattern -- pattern string from which RE obj was compiled</pre>
|
|
<b>Methods:</b>
|
|
<pre>match(string[, pos][, endpos])
|
|
search(string[, pos][, endpos])
|
|
split(string[, maxsplit=0])
|
|
findall(string) [<b>new</b> in 1.5.2]
|
|
sub(repl, string[, count=0])
|
|
subn(repl, string[, count=0]) -- see equivalent functions.</pre>
|
|
<a NAME="matchObject"></a><b>Match Objects</b>
|
|
<br>(Match objects are returned by the match & search functions)
|
|
<p><b>Attributes:</b>
|
|
<pre>pos -- value of pos passed to search or match functions; index into
|
|
string at which RE engine started search.
|
|
endpos -- value of endpos passed to search or match functions; index into
|
|
string beyond which RE engine won't go.
|
|
re -- RE object whose match or search fct produced this MatchObj instance
|
|
string -- string passed to match() or search()</pre>
|
|
<b>Methods:</b>
|
|
<pre>group([g1, g2, ...])
|
|
-- returns one or more groups of the match. If <b>one</b> arg, result is a string;
|
|
if multiple args, result is a tuple with one item per arg. If <i>gi</i> is 0,
|
|
return value is entire matching string; if 1 <= <i>gi</i> <= 99, return
|
|
string matching group #<i>gi</i> (or None if no such group); <i>gi</i> may also be
|
|
a group <i>name</i>.
|
|
groups() -- returns a tuple of all groups of the match; groups not participating
|
|
to the match have a value of None. Returns a string instead of tuple
|
|
if len(tuple)=1
|
|
start(group)
|
|
end(group) -- returns indices of start & end of substring matched by group (or None
|
|
if group exists but doesn't contribute to the match)
|
|
span(group) -- returns the 2-tuple (start(group), end(group)); can be (None, None)
|
|
if group didn't contibute to the match.</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="mathModule"></a><b><i><font size=+2>math</font></i></b></center>
|
|
|
|
<p><b>Variables:</b>
|
|
<pre>pi
|
|
e</pre>
|
|
<b>Functions (see ordinary C man pages for info):</b>
|
|
<pre>acos(x)
|
|
asin(x)
|
|
atan(x)
|
|
atan2(x, y)
|
|
ceil(x)
|
|
cos(x)
|
|
cosh(x)
|
|
exp(x)
|
|
fabs(x)
|
|
floor(x)
|
|
fmod(x, y)
|
|
frexp(x) -- Unlike C: (float, int) = frexp(float)
|
|
ldexp(x, y)
|
|
log(x)
|
|
log10(x)
|
|
modf(x) -- Unlike C: (float, float) = modf(float)
|
|
pow(x, y)
|
|
sin(x)
|
|
sinh(x)
|
|
sqrt(x)
|
|
tan(x)
|
|
tanh(x)</pre>
|
|
|
|
<hr>
|
|
<center><a NAME="getoptModule"></a><b><i><font size=+2>getopt</font></i></b></center>
|
|
|
|
<p><b>Functions:</b>
|
|
<pre>getopt(list, optstr) -- Similar to C. <optstr> is option
|
|
letters to look for. Put ':' after letter
|
|
if option takes arg. E.g.
|
|
# invocation was "python test.py -c hi -a arg1 arg2"
|
|
opts, args = getopt.getopt(sys.argv[1:], 'ab:c:')
|
|
# opts would be
|
|
[('-c', 'hi'), ('-a', '')]
|
|
# args would be
|
|
['arg1', 'arg2']</pre>
|
|
|
|
<pre>
|
|
<hr></pre>
|
|
|
|
<h2>
|
|
<a NAME="OtherModules"></a>List of modules in base distribution</h2>
|
|
|
|
<h3>
|
|
Contents of Lib directory<br>
|
|
<font size=-1>(Python 1.52 NT distribution, may be slightly different in
|
|
other distributions)</font></h3>
|
|
|
|
<pre>aifc -- Stuff to parse AIFF-C and AIFF files.
|
|
anydbm -- Generic interface to all dbm clones. (dbhash, gdbm, dbm,dumbdbm)
|
|
asynchat -- Support for 'chat' style protocols
|
|
asyncore -- Asynchronous File I/O (in <i>select</i> style)
|
|
audiodev -- Audio support for a few platforms.
|
|
base64 -- Conversions to/from base64 RFC-MIME transport encoding .
|
|
BaseHTTPServer -- Base class forhttp services.
|
|
Bastion -- "Bastionification" utility (control access to instance vars)
|
|
bdb -- A generic Python debugger base class.
|
|
binhex -- Macintosh binhex compression/decompression.
|
|
bisect -- List bisection algorithms.
|
|
calendar -- Calendar printing functions.
|
|
cgi -- Wraps the WWW Forms Common Gateway Interface (CGI).
|
|
CGIHTTPServer -- CGI http services.
|
|
cmd -- A generic class to build line-oriented command interpreters.
|
|
cmp -- Efficiently compare files, boolean outcome only.
|
|
cmpcache -- Same, but caches 'stat' results for speed.
|
|
code -- Utilities needed to emulate Python's interactive interpreter
|
|
colorsys -- Conversion functions between RGB and other color systems.
|
|
commands -- Tools for executing UNIX commands .
|
|
compileall -- Force "compilation" of all .py files in a directory.
|
|
ConfigParser -- Configuration file parser (much like windows .ini files)
|
|
copy -- Generic shallow and deep copying operations.
|
|
copy_reg -- Helper to provide extensibility for pickle/cPickle.
|
|
dbhash -- (g)dbm-compatible interface to bsdhash.hashopen.
|
|
dircache -- Sorted list of files in a dir, using a cache.
|
|
dircmp -- Defines a class to build directory diff tools on.
|
|
dis -- Bytecode disassembler.
|
|
dospath -- Common operations on DOS pathnames.
|
|
dumbdbm -- A dumb and slow but simple dbm clone.
|
|
dump -- Print python code that reconstructs a variable.
|
|
exceptions -- Class based built-in exception hierarchy.
|
|
fileinput -- Helper class to quickly write a loop over all standard input files.
|
|
find -- Find files directory hierarchy matching a pattern.
|
|
fnmatch -- Filename matching with shell patterns.
|
|
formatter -- A test formatter.
|
|
fpformat -- General floating point formatting functions.
|
|
ftplib -- An FTP client class. Based on RFC 959.
|
|
getopt -- Standard command line processing.
|
|
getpass -- Utilities to get a password and/or the current user name.
|
|
glob -- filename globbing.
|
|
gopherlib -- Gopher protocol client interface.
|
|
grep -- 'grep' utilities.
|
|
gzip -- Read & write gzipped files.
|
|
htmlentitydefs -- Proposed entity definitions for HTML.
|
|
htmllib -- HTML parsing utilities.
|
|
httplib -- HTTP client class.
|
|
ihooks -- Hooks into the "import" mechanism.
|
|
imaplib -- IMAP4 client.Based on RFC 2060.
|
|
imghdr -- Recognizing image files based on their first few bytes.
|
|
keyword -- List of Python keywords.
|
|
knee -- A Python re-implementation of hierarchical module import.
|
|
linecache -- Cache lines from files.
|
|
locale -- Support for number formatting using the current locale settings.
|
|
macpath -- Pathname (or related) operations for the Macintosh.
|
|
macurl2path -- Mac specific module for conversion between pathnames and URLs.
|
|
mailbox -- A class to handle a unix-style or mmdf-style mailbox.
|
|
mailcap -- Mailcap file handling (RFC 1524).
|
|
mhlib -- MH (mailbox) interface.
|
|
mimetools -- Various tools used by MIME-reading or MIME-writing programs.
|
|
mimetypes -- Guess the MIME type of a file.
|
|
MimeWriter -- Generic MIME writer.
|
|
mimify -- Mimification and unmimification of mail messages.
|
|
multifile -- Class to make multi-file messages easier to handle.
|
|
mutex -- Mutual exclusion -- for use with module sched.
|
|
netrc --
|
|
nntplib -- An NNTP client class. Based on RFC 977.
|
|
ntpath -- Common operations on DOS pathnames.
|
|
nturl2path -- Mac specific module for conversion between pathnames and URLs.
|
|
os -- Either mac, dos or posix depending system.
|
|
packmail -- Create a self-unpacking shell archive.
|
|
pdb -- A Python debugger.
|
|
pickle -- Pickling (save and restore) of Python objects (a faster C
|
|
implementation exists in built-in module: cPickle).
|
|
pipes -- Conversion pipeline templates.
|
|
poly -- Polynomials.
|
|
popen2 -- variations on pipe open.
|
|
poplib -- A POP3 client class. Based on the J. Myers POP3 draft.
|
|
posixfile -- Extended (posix) file operations.
|
|
posixpath -- Common operations on POSIX pathnames.
|
|
pprint -- Support to pretty-print lists, tuples, & dictionaries recursively.
|
|
profile -- Class for profiling python code.
|
|
pstats -- Class for printing reports on profiled python code.
|
|
pty -- Pseudo terminal utilities.
|
|
py_compile -- Routine to "compile" a .py file to a .pyc file.
|
|
pyclbr -- Parse a Python file and retrieve classes and methods.
|
|
Queue -- A multi-producer, multi-consumer queue.
|
|
quopri -- Conversions to/from quoted-printable transport encoding.
|
|
rand -- Don't use unless you want compatibility with C's rand().
|
|
random -- Random variable generators (obsolete, use whrandom)
|
|
re -- Regular Expressions.
|
|
reconvert -- Convert old ("regex") regular expressions to new syntax ("re").
|
|
regex_syntax -- Flags for regex.set_syntax().
|
|
regexp -- Backward compatibility for module "regexp" using "regex".
|
|
regsub -- Regular expression subroutines.
|
|
repr -- Redo repr() but with limits on most sizes.
|
|
rexec -- Restricted execution facilities ("safe" exec, eval, etc).
|
|
rfc822 -- RFC-822 message manipulation class.
|
|
rlcompleter -- Word completion for GNU readline 2.0.
|
|
sched -- A generally useful event scheduler class.
|
|
sgmllib -- A parser for SGML.
|
|
shelve -- Manage shelves of pickled objects.
|
|
shlex -- Lexical analyzer class for simple shell-like syntaxes.
|
|
shutil -- Utility functions usable in a shell-like program.
|
|
SimpleHTTPServer-- Simple extension to base http class
|
|
site -- Append module search paths for third-party packages to sys.path.
|
|
smtplib -- SMTP Client class (RFC 821)
|
|
sndhdr -- Several routines that help recognizing sound.
|
|
SocketServer -- Generic socket server classes.
|
|
stat -- Constants and functions for interpreting stat/lstat struct.
|
|
statcache -- Maintain a cache of file stats.
|
|
statvfs -- Constants for interpreting statvfs struct as returned by os.statvfs()
|
|
and os.fstatvfs() (if they exist).
|
|
string -- A collection of string operations.
|
|
StringIO -- File-like objects that read/write a string buffer (a faster
|
|
C implementation exists in built-in module: cStringIO).
|
|
sunau -- Stuff to parse Sun and NeXT audio files.
|
|
sunaudio -- Interpret sun audio headers.
|
|
symbol -- Non-terminal symbols of Python grammar (from "graminit.h").
|
|
telnetlib -- TELNET client class. Based on RFC 854.
|
|
tempfile -- Temporary file name allocation.
|
|
threading -- Proposed new higher-level threading interfaces
|
|
threading_api -- (doc of the threading module)
|
|
toaiff -- Convert "arbitrary" sound files to AIFF files .
|
|
token -- Tokens (from "token.h").
|
|
tokenize -- Compiles a regular expression that recognizes Python tokens.
|
|
traceback -- Format and print Python stack traces.
|
|
tty -- Terminal utilities.
|
|
turtle -- LogoMation-like turtle graphics
|
|
types -- Define names for all type symbols in the std interpreter.
|
|
tzparse -- Parse a timezone specification.
|
|
urllib -- Open an arbitrary URL.
|
|
urlparse -- Parse URLs according to latest draft of standard.
|
|
user -- Hook to allow user-specified customization code to run.
|
|
UserDict -- A wrapper to allow subclassing of built-in dict class.
|
|
UserList -- A wrapper to allow subclassing of built-in list class.
|
|
util -- some useful functions that don't fit elsewhere !!
|
|
uu -- UUencode/UUdecode.
|
|
wave -- Stuff to parse WAVE files.
|
|
whatsound -- Several routines that help recognizing sound files.
|
|
whichdb -- Guess which db package to use to open a db file.
|
|
whrandom -- Wichmann-Hill random number generator.
|
|
xdrlib -- Implements (a subset of) Sun XDR (eXternal Data Representation)
|
|
xmllib -- A parser for XML, using the derived class as static DTD.
|
|
zmod -- Demonstration of abstruse mathematical concepts.</pre>
|
|
|
|
<h3>
|
|
|
|
<hr WIDTH="100%"></h3>
|
|
|
|
<h3>
|
|
<font size=-1>(following list not revised)<br>
|
|
<br>
|
|
</font>* Built-ins *</h3>
|
|
|
|
<pre> sys Interpreter state vars and functions
|
|
__built-in__ Access to all built-in python identifiers
|
|
__main__ Scope of the interpreters main program, script or stdin
|
|
array Obj efficiently representing arrays of basic values
|
|
math Math functions of C standard
|
|
time Time-related functions
|
|
regex Regular expression matching operations
|
|
marshal Read and write some python values in binary format
|
|
struct Convert between python values and C structs</pre>
|
|
|
|
<h3>
|
|
* Standard *</h3>
|
|
|
|
<pre> getopt Parse cmd line args in sys.argv. A la UNIX 'getopt'.
|
|
os A more portable interface to OS dependent functionality
|
|
re Functions useful for working with regular expressions
|
|
string Useful string and characters functions and exceptions
|
|
whrandom Wichmann-Hill pseudo-random number generator
|
|
thread Low-level primitives for working with process threads
|
|
threading idem, new recommanded interface.</pre>
|
|
|
|
<h3>
|
|
* Unix/Posix *</h3>
|
|
|
|
<pre> dbm Interface to Unix ndbm database library
|
|
grp Interface to Unix group database
|
|
posix OS functionality standardized by C and POSIX standards
|
|
posixpath POSIX pathname functions
|
|
pwd Access to the Unix password database
|
|
select Access to Unix select multiplex file synchronization
|
|
socket Access to BSD socket interface</pre>
|
|
|
|
<h3>
|
|
* Tk User-interface Toolkit *</h3>
|
|
|
|
<pre> tkinter Main interface to Tk</pre>
|
|
|
|
<h3>
|
|
* Multimedia *</h3>
|
|
|
|
<pre> audioop Useful operations on sound fragments
|
|
imageop Useful operations on images
|
|
jpeg Access to jpeg image compressor and decompressor
|
|
rgbimg Access SGI imglib image files</pre>
|
|
|
|
<h3>
|
|
* Cryptographic Extensions *</h3>
|
|
|
|
<pre> md5 Interface to RSA's MD5 message digest algorithm
|
|
mpz Interface to int part of GNU multiple precision library
|
|
rotor Implementation of a rotor-based encryption algorithm</pre>
|
|
|
|
<h3>
|
|
* Stdwin * Standard Window System</h3>
|
|
|
|
<pre> stdwin Standard Window System interface
|
|
stdwinevents Stdwin event, command, and selection constants
|
|
rect Rectangle manipulation operations</pre>
|
|
|
|
<h3>
|
|
* SGI IRIX * (4 & 5)</h3>
|
|
|
|
<pre> al SGI audio facilities
|
|
AL al constants
|
|
fl Interface to FORMS library
|
|
FL fl constants
|
|
flp Functions for form designer
|
|
fm Access to font manager library
|
|
gl Access to graphics library
|
|
GL Constants for gl
|
|
DEVICE More constants for gl
|
|
imgfile Imglib image file interface</pre>
|
|
|
|
<h3>
|
|
* Suns *</h3>
|
|
|
|
<pre> sunaudiodev Access to sun audio interface</pre>
|
|
|
|
<hr WIDTH="100%">
|
|
<h2>
|
|
<a NAME="Workspace"></a>Workspace exploration and idiom hints</h2>
|
|
|
|
<pre> dir(<module>) list functions, variables in <module>
|
|
dir() get object keys, defaults to local name space
|
|
X.__methods__ list of methods supported by X (if any)
|
|
X.__members__ List of X's data attributes
|
|
if __name__ == '__main__': main() invoke main if running as script
|
|
map(None, lst1, lst2, ...) merge lists
|
|
b = a[:] create copy of seq structure
|
|
_ in interactive mode, is last value printed
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<hr></pre>
|
|
|
|
<h2>
|
|
<a NAME="Emacs"></a>Python Mode for Emacs</h2>
|
|
|
|
<pre><b><font size=-1>(Not revised, possibly not up to date)</font></b></pre>
|
|
|
|
<pre>Type C-c ? when in python-mode for extensive help.
|
|
|
|
INDENTATION
|
|
|
|
Primarily for entering new code:
|
|
TAB indent line appropriately
|
|
LFD insert newline, then indent
|
|
DEL reduce indentation, or delete single character
|
|
|
|
Primarily for reindenting existing code:
|
|
C-c : guess py-indent-offset from file content; change locally
|
|
C-u C-c : ditto, but change globally
|
|
|
|
C-c TAB reindent region to match its context
|
|
C-c < shift region left by py-indent-offset
|
|
C-c > shift region right by py-indent-offset
|
|
|
|
|
|
MARKING & MANIPULATING REGIONS OF CODE
|
|
|
|
C-c C-b mark block of lines
|
|
M-C-h mark smallest enclosing def
|
|
C-u M-C-h mark smallest enclosing class
|
|
C-c # comment out region of code
|
|
C-u C-c # uncomment region of code
|
|
|
|
MOVING POINT
|
|
|
|
C-c C-p move to statement preceding point
|
|
C-c C-n move to statement following point
|
|
C-c C-u move up to start of current block
|
|
M-C-a move to start of def
|
|
C-u M-C-a move to start of class
|
|
M-C-e move to end of def
|
|
C-u M-C-e move to end of class
|
|
|
|
EXECUTING PYTHON CODE
|
|
|
|
C-c C-c sends the entire buffer to the Python interpreter
|
|
C-c | sends the current region
|
|
C-c ! starts a Python interpreter window; this will be used by
|
|
subsequent C-c C-c or C-c | commands
|
|
|
|
VARIABLES
|
|
|
|
py-indent-offset indentation increment
|
|
py-block-comment-prefix comment string used by py-comment-region
|
|
|
|
py-python-command shell command to invoke Python interpreter
|
|
py-scroll-process-buffer t means always scroll Python process buffer
|
|
py-temp-directory directory used for temp files (if needed)
|
|
|
|
|
|
py-beep-if-tab-change ring the bell if tab-width is changed</pre>
|
|
|
|
<hr>
|
|
<h2>
|
|
<a NAME="Debugger"></a>The Python Debugger</h2>
|
|
|
|
<pre><b><font size=-1>(Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE)</font></b></pre>
|
|
|
|
<h3>
|
|
Accessing</h3>
|
|
|
|
<pre>import <b>pdb</b> (it's a module written in Python)
|
|
|
|
-- defines <b>functions :
|
|
</b> run(statement[,globals[, locals]])
|
|
-- execute statement string under debugger control, with optional
|
|
global & local environment.
|
|
runeval(expression[,globals[, locals]])
|
|
-- same as run, but evaluate expression and return value.
|
|
runcall(function[, argument, ...])
|
|
-- run function object with given arg(s)
|
|
pm() -- run postmortem on last exception (like debugging a core file)
|
|
post_mortem(t)
|
|
-- run postmortem on traceback object <t>
|
|
|
|
-- defines <b>class Pdb :
|
|
</b> use Pdb to create reusable debugger objects. Object
|
|
preserves state (i.e. break points) between calls.
|
|
|
|
|
|
runs until a breakpoint hit, exception, or end of program
|
|
If exception, variable '__exception__' holds (exception,value).</pre>
|
|
|
|
<h3>
|
|
Commands</h3>
|
|
|
|
<pre>h, help
|
|
brief reminder of commands
|
|
b, break [<arg>]
|
|
if <arg> numeric, break at line <arg> in current file
|
|
if <arg> is function object, break on entry to fcn <arg>
|
|
if no arg, list breakpoints
|
|
cl, clear [<arg>]
|
|
if <arg> numeric, clear breakpoint at <arg> in current file
|
|
if no arg, clear all breakpoints after confirmation
|
|
w, where
|
|
print current call stack
|
|
u, up
|
|
move up one stack frame (to top-level caller)
|
|
d, down
|
|
move down one stack frame
|
|
s, step
|
|
advance one line in the program, stepping into calls
|
|
n, next
|
|
advance one line, stepping over calls
|
|
r, return
|
|
continue execution until current function returns
|
|
(return value is saved in variable "__return__", which
|
|
can be printed or manipulated from debugger)
|
|
c, continue
|
|
continue until next breakpoint
|
|
a, args
|
|
print args to current function
|
|
rv, retval
|
|
prints return value from last function that returned
|
|
p, print <arg>
|
|
prints value of <arg> in current stack frame
|
|
l, list [<first> [, <last>]]
|
|
List source code for the current file.
|
|
Without arguments, list 11 lines around the current line
|
|
or continue the previous listing.
|
|
With one argument, list 11 lines starting at that line.
|
|
With two arguments, list the given range;
|
|
if the second argument is less than the first, it is a count.
|
|
whatis <arg>
|
|
prints type of <arg>
|
|
!
|
|
executes rest of line as a Python statement in the current stack frame
|
|
q quit
|
|
immediately stop execution and leave debugger
|
|
|
|
<return>
|
|
executes last command again
|
|
|
|
Any input debugger doesn't recognize as a command is assumed to be a
|
|
Python statement to execute in the current stack frame, the same way
|
|
the exclamation mark ("!") command does.</pre>
|
|
|
|
<h3>
|
|
Example</h3>
|
|
|
|
<pre>(1394) python
|
|
Python 1.0.3 (Sep 26 1994)
|
|
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
|
|
>>> import rm
|
|
>>> rm.run()
|
|
Traceback (innermost last):
|
|
File "<stdin>", line 1
|
|
File "./rm.py", line 7
|
|
x = div(3)
|
|
File "./rm.py", line 2
|
|
return a / r
|
|
ZeroDivisionError: integer division or modulo
|
|
>>> import pdb
|
|
>>> pdb.pm()
|
|
> ./rm.py(2)div: return a / r
|
|
(Pdb) list
|
|
1 def div(a):
|
|
2 -> return a / r
|
|
3
|
|
4 def run():
|
|
5 global r
|
|
6 r = 0
|
|
7 x = div(3)
|
|
8 print x
|
|
[EOF]
|
|
(Pdb) print r
|
|
0
|
|
(Pdb) q
|
|
>>> pdb.runcall(rm.run)
|
|
etc.</pre>
|
|
|
|
<h3>
|
|
Quirks</h3>
|
|
Breakpoints are stored as filename, line number tuples. If a module is
|
|
reloaded after editing, any remembered breakpoints are likely to be wrong.
|
|
<p>Always single-steps through top-most stack frame. That is, "c" acts
|
|
like "n".
|
|
</body>
|
|
</html>
|