Escolar Documentos
Profissional Documentos
Cultura Documentos
7 Q ui ck Ref er en ce
Con ten ts
Front matter
Inv ocation Options
Env ironm ent v ariables
Lex ical entities : key words, identifiers, string literals, boolean constants, numbers, sequences, dictionaries, sets,
operators
Basic ty pes and their operations: None, bool, Numeric ty pes, sequence ty pes, list, dictionary , string, file, set, named
tuples, date/time
Adv anced ty pes
Statem ents: assignment, conditional ex pressions, control flow, ex ceptions, name space, function def, class def
Iterators; Generators; Descriptors; Decorators
Built-in Functions
Built-in Ex ceptions
Standard m ethods & operators redefinition in user-created Classes
Special inform ativ e state attributes for some ty pes
Important m odules : sy s, os, posix , posix path, shutil, time, string, re, math, compressions
List of m odules in the base distribution
Workspace ex ploration and idiom hints
Py thon mode for Emacs
Fr on t ma tter
Version 2.7 (What's new?)
Check updates at http://rgruet.free.fr/#QuickRef.
Please report errors, inaccuracies and suggestions to Richard Gruet (pqr at rgruet.net).
Creativ e Commons License.
Color coding:
Fea t u r es a dded in 2 .7 sin ce 2 .6
Fea t u r es a dded in 2 .6 sin ce 2 .5
Fea t u r es a dded in 2 .5 sin ce 2 .4
A lin k
Effect
-B
-d
-E
-h
-i
-m
module
-O
-OO
-Q arg
-s
-S
-t
-u
-U
-v
-V
-W arg
-x
-X
-3
-c
command
scriptFile
args
Prev ents m odule im por ts from cr eating .pyc or .pyo files (see also env t v ariable PYTHONDONTWRITEBYTECODE=x and
attribu te sys.dont_write_bytecode ).
Output parser debu gging inform ation (also PYTHONDEBUG= x)
Ignor e env ironm ent v ariables (su ch as PYTHONPATH)
Print a help m essage and exit (for m er ly -?)
Inspect inter activ ely after running scr ipt (also PYTHONINSPECT=x) and force pr om pts, ev en if stdin appears not to be
a ter m inal.
Search for module on sys.path and r uns the m odule as a script. (Im plem entation im pr ov ed in 2 .5: m odu le runpy )
Optim ize generated by tecode (also PYTHONOPTIMIZE= x). Asserts are su ppressed.
Rem ov e doc-strings in addition to the -O optim izations.
Div ision options: -Qold (default), -Qw ar n, -Qw ar nall, -Qnew
Disables the u ser-specific m odule path (also PYTHONNOUSERSITE= x)
Don't perform import site on initialization.
Issu e warnings about inconsistent tab u sage (-tt: issu e errors).
Unbuffered binar y stdou t and stder r (also PYTHONUNBUFFERED= x).
Force Py thon to inter pr et all string literals as Unicode literals.
Verbose (trace im port statem ents) (also PYTHONVERBOSE= x).
Print the Py thon v er sion nu m ber and exit.
Warning control (arg is action:m essage:category :m odu le:lineno)
Skip fir st line of source, allow ing use of non-u nix Form s of #!cmd
Disable class based built-in exceptions (for backw ard com patibility m anagem ent of exceptions)
Em it a DeprecationWarning for Py thon 3 .x incom patibilities that 2to3 cannot triv ially fix
Specify the com m and to execu te (see next section). This term inates the option list (following options are passed as
argum ents to the com m and).
The nam e of a py thon file (.py ) to execute. Read fr om stdin.
Program r ead fr om stdin (default; interactiv e m ode if a tty ).
Passed to scr ipt or com m and (in sys.argv[1:] )
If no scriptFile or com m and, Py thon enters interactiv e m ode.
A v ailable IDEs in std distrib: IDLE (tkinter based, portable), Py thonwin (on Windows). Other free IDEs: IPy thon
(enhanced interactiv e Py thon shell - 201 1 ), Eric (201 1 ), SPE (2010), BOA constructor (GUI Builder - 201 1 ), Py Dev
(Eclipse plugin - 201 1).
Ty pical py thon m odule header :
#!/usr/bin/env python
# -*- coding: latin1 -*-
Since 2.3 the encoding of a Py thon source file must be declared as one of the two first lines (or defaults to 7 bits Ascii)
[PEP-0263], with the format:
# -*- coding: encoding -*-
Std encodings are defined here, e.g. ISO-8859-1 (aka latin1 ), iso-8859-1 5 (latin9), UTF-8... Not all encodings supported,
in particular UTF-1 6 is not supported.
It's now a sy ntax error if a module contains string literals with 8-bit characters but doesn't hav e an encoding
It's now a sy ntax error if a module contains string literals with 8-bit characters but doesn't hav e an encoding
declaration (was a warning before).
Since 2.5, from __future__ import feature statements must be declared at beginning of source file.
Site custom ization: File sitecustomize.py is automatically loaded by Py thon if it ex ists in the Py thon path (ideally
located in ${PYTHONHOME}/lib/site-packages/).
T ip: when launching a Py thon script on Windows,
<pythonHome>\python myScript.py args ... can be redu ced to :
myScript.py args ... if < py thonHom e> is in the PATH env t v ar iable, and further redu ced to :
myScript args ... pr ov ided that .py;.pyw;.pyc;.pyo is added to the PATHEXT env t v ar iable.
Effect
Alternate prefix dir ector y (or prefix:exec_prefix). The default m odule search path uses prefix/lib
Au gm ents the defau lt search path for m odu le files. The for m at is the sam e as the shell's $PATH :
one or m ore dir ector y pathnam es separated by ':' or ';' without spaces arou nd (sem i-) colons !
On Windows Py thon first searches for Registr y key
HKEY_LOCAL_MACHINE\Software\Python\PythonCore\x.y\PythonPath (defau lt v alue). You
can create a key nam ed after y our application with a default string v alue giv ing the root
dir ector y path of y our appl.
PYTHONHOME
PY THONPATH
PYTHONSTARTUP
PYTHONDEBUG
PYTHONINSPECT
PYTHONOPTIMIZE
PYTHONUNBUFFERED
PYTHONVERBOSE
PYTHONCASEOK
PYTHONDONTWRITEBYTECODE
PYTHONIOENCODING
PYTHONUSERBASE
PYTHONNOUSERSITE
PYTHONWARNINGS
Alternativ ely , y ou can cr eate a text file with a .pth extension, containing the path(s), one per
line, and put the file som ew her e in the Py thon sear ch path (ideally in the site-packages/
dir ector y ). It's better to create a .pth for each application, to m ake easy to u ninstall them .
If this is the nam e of a readable file, the Py thon com m ands in that file are executed befor e the
first prom pt is display ed in interactiv e m ode (no defau lt).
If non-em pty , sam e as -d option
If non-em pty , sam e as -i option
If non-em pty , sam e as -O option
If non-em pty , sam e as -u option
If non-em pty , sam e as -v option
If non-em pty , ignore case in file/m odu le nam es (im ports)
If non-em pty , sam e as -B option
Alternate encodingname or encodingname:errorhandler for stdin, stdou t, and stderr, with
the sam e choices accepted by str.encode() .
Pr ov ides a pr iv ate site-packages dir ectory for user-specific m odu les. [PEP-03 7 0]
- On Unix and Mac OS X, defau lts to ~/.local/ , and m odu les ar e fou nd in a v ersion-specific
su bdir ector y like lib/python2.6/site-packages .
- On Windows, defaults to %APPDATA%/Python and Python26/site-packages.
If non-em pty , sam e as -s option
Allow s controlling warnings, sam e as -W option
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
I dent ifiers
(letter | "_") (letter | digit | "_")*
Mea n i n g
\newline
\\
\e
\v
\'
\f
\ooo
\"
\n
\a
\r
\xhh
\b
\t
\uxxxx
\Uxxxxxxxx
\N{name}
\AnyOtherChar
Boolean constants
True
False
Since 2 .3 , they are of new ty pe bool .
Numbers
Decimal integer: 1234, 1234567890546378940L (or l)
Binary integer : 0b10, 0B10, 0b10101010101010101010101010101010L (begins w ith a 0b or 0B )
Oct al integer : 0177, 0o177, 0O177, 0177777777777777777L (begins w ith a 0 , 0o, or 0O )
Hex integer : 0xFF, 0XFFFFffffFFFFFFFFFFL (begins with 0x or 0X )
Long integer (unlim ited precision): 1234567890123456L (ends with L or l ) or long(1234)
Float (double precision): 3.14e-10, .001, 10., 1E3
Complex: 1J, 2+3J, 4+5j (ends with J or j , + separ ates (float) r eal and im aginar y par ts)
Integers and long integers are unified starting fr om release 2 .2 (the L su ffix is no longer requ ired)
Sequences
Str ings and tuples are im m u table, lists are m utable.
Strings (ty pes str and unicode ) of length 0, 1 , 2 (see abov e)
'', '1 ', "1 2 ", 'hello\n'
Tuples (ty pe tuple) of length 0, 1 , 2 , etc:
() (1 ,) (1 ,2 ) # parentheses ar e optional if len > 0
Lists (ty pe list) of length 0, 1 , 2 , etc:
[] [1 ] [1 ,2 ]
Index ing is 0-based. Negativ e indices (usually ) mean count backwards from end of sequence.
Sequence slicing [starting-at-index : but-less-than-index [ : step]]. Start defaults to 0, end to len(sequence), step to 1.
Sequence slicing [starting-at-index : but-less-than-index [ : step]]. Start defaults to 0, end to len(sequence), step to 1.
a = (0,1,2,3,4,5,6,7)
a[3] == 3
a[-1] == 7
a[2:4] == (2, 3)
a[1:] == (1, 2, 3, 4, 5, 6, 7)
a[:3] == (0, 1, 2)
a[:] == (0,1,2,3,4,5,6,7) # makes a copy of the sequence.
a[::2] == (0, 2, 4, 6) # Only even numbers.
a[::-1] = (7, 6, 5, 4, 3 , 2, 1, 0) # Reverse order.
Dictionaries ( Mappings)
Dictionaries (ty pe dict ) of length 0, 1 , 2 , etc: {key: value} {1 : 'fir st'} {1 : 'first', 'two': 2 , key:value}
Sets
A set kan either be mutable or immutable. Curly brackets ({} ) are used to surround the contents of the resulting mutable set; set
literals are distinguished from dictionaries by not containing colons and v alues. An empty {} continues to represent an empty
dictionary ; use set() for an empty set.
Com m en t
Lowest
A lternate names are defined in module operator (e.g. __add__ and add for +)
Most operators are ov erridable
<
<=
>
>=
==
!= or <>
is
is not
Not es
(1 )
(2 )
(2 )
Notes:
Comparison behav ior can be ov erridden for a giv en class by defining special method __cmp__.
(1 ) X < Y < Z < W has ex pected meaning, unlike C
(2) Compare object identities (i.e. id(object)), not object v alues.
None
None is u sed as default retur n v alue on functions. Built-in single object w ith ty pe NoneType . Might becom e a key w ord in the
futur e.
Inpu t that ev aluates to None does not print w hen running Py thon inter activ ely .
None is now a constant; try ing to bind a v alue to the nam e "None" is now a sy ntax error.
None is now a constant; try ing to bind a v alue to the nam e "None" is now a sy ntax error.
Boolean operators
Boolean values and operators
V a l u e or Oper a t or
Ev a l u a t es t o
built-in bool(expr)
None, num er ic zeros, em pty sequ ences and m appings
all other v alues
not x
x or y
x and y
Not es
(1 )
(1 )
Notes:
Truth testing behav ior can be ov erridden for a giv en class by defining special method __nonzero__.
(1 ) Ev aluate second arg only if necessary to determine outcome.
Numeric types
Fl o a t s , in t e g e rs , l o n g in t e g e rs , De c im a ls .
Floats (ty pe float ) are im plem ented w ith C doubles.
Integer s (ty pe int ) are im plem ented with C longs (signed 3 2 bits, m axim um v alue is sys.maxint )
Long integer s (ty pe long ) hav e unlim ited size (only lim it is sy stem resources).
Integer s and long integers ar e unified starting fr om release 2 .2 (the L suffix is no longer r equir ed). int() retu rns a long
integer instead of r aising OverflowError . Ov erflowing operations such as 2<<32 no longer tr igger FutureWarning and
retur n a long integer .
Since 2 .4, new ty pe Decimal introdu ced (see m odule: decim al) to com pensate for som e lim itations of the floating point ty pe,
in particu lar w ith fractions. Unlike floats, decim al nu m bers can be represented exactly ; exactness is preser v ed in
calcu lations; precision is user settable v ia the Context ty pe [PEP 3 2 7 ].
Op e ra t o rs o n a l l n u m e ric t y p e s
Operators on all numeric types
Oper a t i on
Resu l t
abs(x)
int (x)
long(x)
float (x)
-x
+x
x+ y
x-y
x*y
x/y
x // y
x%y
divmod(x, y)
x ** y
Not es
(2 )
(2 )
(1 )
(1 )
Notes:
(1 ) / is still a floor div ision (1 /2 == 0) unless v alidated by a from __future__ import division .
(2) int and long has bit_length() method that returns the number of bits necessary to represent its argument in binary .
classes may ov erride methods __truediv__ and __floordiv__ to redefine these operators.
Bit o p e ra t o rs o n in t e g e rs a n d l o n g in t e g e rs
Bit operators
Oper a t i on Resu lt
~x
x^y
x&y
x|y
x << n
x >> n
Co m p l e x Nu m b e rs
Ty pe complex , represented as a pair of machine-lev el double precision floating point numbers.
The real and imaginary v alue of a complex number z can be retriev ed through the attributes z.real and z.imag.
Nu m e ric e x c e p t io n s
TypeError
r a ised on a pplic a t ion of a r it h m et ic oper a tion t o n on -n u m ber
OverflowError
n u m er ic bou n ds ex c eeded
ZeroDivisionError
r a ised w h en zer o sec on d a r g u m en t of div or m odu lo op
x in s
x not in s
s1 + s2
s * n, n*s
s[i]
s[i: j]
s[i: j:step]
s.count (x)
s.index(x[, start[,
stop]])
len(s)
min(s)
max(s)
rev ersed(s)
sorted(iterable [, cmp]
[, cm p= cmpFunc]
[, key = keyGetter]
[, rev erse= bool])
Resu lt
True if an item of s is equal to x, else False
False if an item of s is equal to x, else True
Not es
(3 )
(3 )
(1 )
(1 ), (2 )
(4)
Length of s
Sm allest item of s
Largest item of s
[2 .4 ] Retu rns an iterator on s in rev erse order. s m u st be a sequence, not an iterator (u se
reversed(list(s)) in this case. [PEP 3 2 2 ]
[2 .4 ] works like the new in-place list.sor t(), but sor ts a new list created from the iterable.
Notes:
(1 ) if i or j is negativ e, the index is relativ e to the end of the string, ie len(s)+i or len(s)+j is substituted. But note that -0 is
still 0.
(2) The slice of s from i to j is defined as the sequence of items with index k such that i<= k < j.
If i or j is greater than len(s), use len(s). If j is omitted, use len(s). If i is greater than or equal to j, the slice is empty .
(3) For strings: x in s is True if x is a substring of s.
(4) Raises a ValueError ex ception when x is not found in s (i.e. out of range).
list)
s[i] =x
s[i:j [:step]] = t
del s[i:j[:step]]
s.append(x)
s.ext end(x)
s.count (x)
s.index(x[, start[, stop]])
s.insert(i, x)
s.remove(x)
s.pop([i])
s.reverse()
s.sort ([cmp ])
Resu lt
Not es
item i of s is r eplaced by x
slice of s from i to j is replaced by t
sam e as s[i:j] = []
sam e as s[len(s) : len(s)] = [x]
sam e as s[len(s):len(s)]= x
retu rns num ber of i's for which s[i] = = x
retu rns sm allest i such that s[i]= = x. start and stop lim it search to only part of
the list.
sam e as s[i:i] = [x] if i> = 0. i = = -1 inserts before the last elem ent.
sam e as del s[s.index(x)]
sam e as x = s[i]; del s[i]; retu rn x
rev erses the item s of s in place
sorts the item s of s in place
(6 )
(5) (6)
(1 )
(1 )
(4 )
(3 )
(2 ), (3 )
Notes:
(1 ) Raises a ValueError ex ception when x is not found in s (i.e. out of range).
(2) The sort() method takes an optional argument cmp specify ing a comparison function taking 2 list items and returning
-1 , 0, or 1 depending on whether the 1 st argument is considered smaller than, equal to, or larger than the 2nd argument.
Note that this slows the sorting process down considerably . Since 2.4, 2 optional key words args are added: key is a
function of one argument that used to ex tract a comparison key from each list element (faster than cmp). Also, see
attrgetter and itemgetter in the operator module. reverse : If True, rev erse the sense of the comparison used.
Since Py thon 2.3, the sort is guaranteed "stable". This means that two entries with equal key s will be returned in the same
order as they were input. For ex ample, y ou can sort a list of people by name, and then sort the list by age, resulting in a
list sorted by age where people with the same age are in name-sorted order.
(3) The sort() and reverse() methods m odify the list in place for economy of space when sorting or rev ersing a large
list. They don't return the sorted or rev ersed list to remind y ou of this side effect.
(4) The pop() method is not supported by mutable sequence ty pes other than lists. The optional argument i defaults to -1 ,
so that by default the last item is remov ed and returned.
(5) Raises a TypeError when x is not a list object.
(6) append v s. ex tend: append takes any object and places as last element in list, while ex tend only takes a iterable object
and ex tends the list with each element in x .
dict)
Operations on mappings
Oper a t i on
Resu l t
Not es
len(d)
dict()
dict(**kwargs)
dict(iterable)
dict(d)
d.fromkeys(iterable, value= None)
d[k]
d[k] = x
del d[k]
d.clear()
d.copy ()
d.has_key(k)
k in d
d.items()
d.keys()
d1.update(d2)
d.values()
d.get (k [, defaultval])
d.setdefault (k[,defaultval])
d.iterit ems()
d.iterkeys()
d.itervalues()
d.pop(k[, default])
d.popitem()
d.viewitems()
d.viewkey s()
d.viewv alues()
(1 )
(1 )
(2 )
(2 )
(2 )
(3 )
(4)
(5)
(5)
(5)
Notes:
TypeError is raised if key is not acceptable.
(1 ) KeyError is raised if key k is not in the map.
str
&
unicode)
These string methods largely (but not completely ) supersede the functions av ailable in the string module.
The str and unicode ty pes share a common base class basestring .
Operations on strings
Oper a t i on
s.capitalize()
s.cent er(width[, fillChar= ' '])
s.count (sub[, start[, end]])
s.decode([encoding[, errors]])
s.encode([encoding[, errors]])
Resu l t
Retur ns a copy of s w ith its fir st char acter capitalized, and the r est of the
character s lower cased.
Retur ns a copy of s center ed in a string of length width, surr ounded by the
appropr iate num ber of fillChar character s.
Retur ns the num ber of occurr ences of su bstring sub in string s.
Retur ns a unicode string representing the decoded v er sion of str s, u sing the
giv en codec (encoding). Useful w hen r eading from a file or a I/O function that
handles only str . Inv er se of encode.
Retur ns a str repr esenting an encoded v ersion of s. Mostly u sed to encode a
unicode str ing to a str in order to print it or write it to a file (since these I/O
functions only accept str ), e.g. u'lgre'.encode('utf8') . Also used to encode
a str to a str , e.g. to zip (codec 'zip') or uu encode (codec 'u u') it. Inv er se of
decode.
Retur ns True if s ends w ith the specified suffix, other wise retu rn false. Since 2 .5
suffix can also be a tuple of strings to try .
Retur ns a copy of s w her e all tab characters are expanded u sing spaces.
Retur ns the lowest index in s w her e su bstring sub is found. Retur ns -1 if sub is not
found.
Retur ns s after r eplacing nu m eric and nam ed form atting refer ences found in
br aces {} . (details)
like find(), but r aises ValueError w hen the su bstring is not fou nd.
Retur ns True if all characters in s are alphanum eric, False otherw ise.
Retur ns True if all characters in s are alphabetic, False otherw ise.
Retur ns True if all characters in s are digit characters, False otherw ise.
Retur ns True if all characters in s are lower case, False other wise.
Retur ns True if all characters in s are w hitespace char acters, False other wise.
Retur ns True if string s is a titlecased str ing, False otherwise.
Retur ns True if all characters in s are upper case, False other wise.
Retur ns a concatenation of the strings in the sequ ence seq, separated by string
separator, e.g.: ",".join(['A', 'B', 'C']) -> "A,B,C"
Not es
(1 )
(2 )
(3 )
(3 )
(2 )
(4)
(2 )
(2 )
(5)
(5)
(5)
(6)
(5)
(7 )
(6)
s.rst rip([chars])
s.split ([ separator[, maxsplit]])
s.rsplit ([ separator[, maxsplit]])
s.split lines([ keepends])
s.startswith(prefix [, start[, end]])
s.strip([chars])
s.swapcase()
s.t it le()
s.t ranslate(table[, deletechars= ''])
s.upper()
s.zfill(width)
(1 ), (8)
(9)
(2 )
(2 )
(1 0)
(1 0)
(1 1 )
(2 )
(1 2 )
Notes:
(1 ) Padding is done using spaces or the giv en character.
(2) If optional argument start is supplied, substring s[start:] is processed. If optional arguments start and end are
supplied, substring s[start:end] is processed.
(3) Default encoding is sys.getdefaultencoding() , can be changed v ia sys.setdefaultencoding() . Optional argument
errors may be giv en to set a different error handling scheme. The default for errors is 'strict', meaning that encoding
errors raise a ValueError. Other possible v alues are 'ignore' and 'replace'. See also module codecs.
(4) If optional argument tabsize is not giv en, a tab size of 8 characters is assumed.
(5) Returns False if string s does not contain at least one character.
(6) Returns False if string s does not contain at least one cased character.
(7 ) A titlecased string is a string in which uppercase characters may only follow uncased characters and lowercase
characters only cased ones.
(8) s is returned if w idth is less than len(s).
(9) If the optional argument maxCount is giv en, only the first maxCount occurrences are replaced.
(1 0) If separator is not specified or None , any whitespace string is a separator. If maxsplit is giv en, at most maxsplit splits
are done.
(1 1 ) Line breaks are not included in the resulting list unless keepends is giv en and true.
(1 2) table must be a string of length 256.
St rin g fo rm a t t in g w it h t h e % o p e ra t o r
formatString % args --> ev aluates to a str ing
Resu l t
' 2'
' 2'
'2 '
'002'
' 2'
'+2'
' -2'
' 2 '
'2.0000'
'%.4f' % 2
'%.*f' % (4, 2)
'%0*.*f' % (10, 4, 2)
'%10.4f' % 2
'%010.4f' % 2
'2.0000'
'2.0000'
'00002.0000'
' 2.0000'
'00002.0000'
d
i
o
u
x
X
e
E
f
F
g
G
c
r
s
%
Mea n i n g
#
0
+
St rin g t e m p la t in g
Since 2.4 [PEP 292] the string module prov ides a new mechanism to substitute v ariables into template strings.
Variables to be substituted begin with a $. A ctual v alues are prov ided in a dictionary v ia the substitute or safe_substitute
methods (substitute throws KeyError if a key is missing while safe_substitute ignores it) :
t = string.Template('Hello $name, you won $$$amount') # (note $$ to literalize $)
t.substitute({'name': 'Eric', 'amount': 100000}) # -> u'Hello Eric, you won $100000'
St rin g fo rm a t t in g w it h fo rm a t ()
Since 2.6 [PEP 31 01] string formatting can also be done with the format() method:
"string-to-format".form at(args)
Format fields are specified in string-to-format, surrounded by {} , while actual v alues are args to format() :
{[field][!conversion][:format_spec]}
Each field refers to an arg either by its position (>=0), or by its name if it's a keyw ord argument. If left out, automatic
numbering is used, so the first {...} specifier will use the first argument, the nex t specifier will use the nex t argument,
and so on. Autonumbering cannot be mix ed with ex plicit numbering, but it can be mix ed with named fields. The same arg
can be referenced more than once.
The conversion can be !s or !r to call str() or repr() on the field before formatting.
The format_spec takes the following form:
[[fill]align][sign][#][0][width][,][.precision][type]
The align flag controls the alignment when padding v alues (see table below), and can be preceded by a fill
character. A fill cannot be used on its own.
The sign flag controls the display of signs on numbers (see table below).
The # flag adds a leading 0b , 0o, or 0x for binary , octal, and hex conv ersions.
The 0 flag zero-pads numbers, equiv alent to hav ing a fill-align of 0=.
The width is a number giv ing the minimum field width. Padding will be added according to align until this width is
achiev ed.
The , option indicates that commas should be included in the output as a thousands separator.
The , option indicates that commas should be included in the output as a thousands separator.
For floating-point conv ersions, precision giv es the number of places to display after the decimal point. For nonnumeric conv ersion, precision giv es the max imum field width.
The type specifies how to present numeric ty pes (see tables below).
Braces can be doubled ({{ or }} ) to insert a literal brace character.
Alignment flag characters
Fl a g Mea n i n g
<
>
=
^
Left-aligns the field and pads to the right (default for non-num bers)
Right-aligns the field and pads to the left (defau lt for nu m ber s)
Inserts padding betw een the sign and the field (num bers only )
Aligns the field to the center and pads both sides
+
-
b
c
d
o
x
X
e
E
f
F
g
G
n
%
file)
(Ty pe file ). Created with built-in functions open() [preferred] or its alias file() . May be created by other modules' functions as
well.
Unicode file names are now supported for all functions accepting or returning file names (open, os.listdir, etc...).
Op e ra t o rs o n fil e o b je c t s
File operations
Oper a t i on
f.close()
f.fileno()
f.flush()
f.isatty ()
f.next ()
f.read([size])
f.readline()
f.readlines()
f.xreadlines()
for line in f: do som ething...
f.seek(offset[, whence= 0])
f.tell()
f.truncate([size])
f.writ e(str)
f.writ elines(list)
Resu lt
Close file f.
Get fileno (fd) for file f.
Flush file f's internal buffer.
1 if file f is connected to a tty -like dev , else 0.
Retu rns the next input line of file f, or r aises StopIteration when EOF is hit. Files ar e their ow n
iterators. next is im plicitly called by constru cts like for line in f: print line .
Read at m ost size by tes from file f and retu rn as a string object. If size om itted, read to EOF.
Read one entire line from file f. The returned line has a trailing \n, except possibly at EOF. Return ''
on EOF.
Read until EOF w ith readline() and retu rn a list of lines read.
Retu rn a sequ ence-like object for reading a file line-by -line without reading the entire file into
m em or y . From 2 .2 , u se rather: for line in f (see below).
Iterate ov er the lines of a file (using r eadline)
Set file f's position, like "stdio's fseek()".
whence = = 0 then use absolute indexing.
whence = = 1 then offset relativ e to cu rrent pos.
whence = = 2 then offset relativ e to file end.
Retu rn file f's cu rrent position (by te offset).
Tru ncate f's size. If size is present, f is tru ncated to (at m ost) that size, otherw ise f is truncated at
cur rent position (w hich rem ains unchanged).
Wr ite string to file f.
Wr ite list of strings to file f. No EOL are added.
Fil e Ex c e p t io ns
EOFError
En d-of-file h it w h en r ea din g (m a y be r a ised m a n y t im es, e. g . if f is a t t y ).
IOError
set
&
frozenset)
set and frozenset (immutable set). Sets are unordered collections of unique (non duplicate) elements. Elements must be
hashable. frozensets are hashable (thus can be elements of other sets) while sets are not. A ll sets are iterable.
A set may be created with set(iterable) or curly brackets ({} ), which also allows for list comprehensions, using curly brackets
set/frozenset([iterable= None])
len(s)
elt in s / not in s
for elt in s: process elt...
s1.issubset (s2)
s1.issuperset(s2)
s.add(elt)
s.remove(elt)
s.discard(elt)
s.pop()
s.clear()
s1.int ersection(s2[, s3...]) or s1&s2
s1.union(s2[, s3...]) or s1|s2
s1.difference(s2[, s3...]) or s1-s2
s1.symmet ric_difference(s2) or s1^s2
s.copy()
s.updat e(iterable1[, iterable2...])
Resu l t
[using built-in ty pes] Builds a set or frozenset from the giv en iterable (default:
em pty ), e.g. set([1,2,3]) , set("hello") .
Car dinality of set s.
True if elem ent elt belongs / does not belong to set s.
Iter ates on elem ents of set s.
True if ev er y elem ent in s1 is in iterable s2.
True if ev er y elem ent in s2 is in iterable s1.
Adds elem ent elt to set s (if it doesn't already exist).
Rem ov es elem ent elt fr om set s. KeyError if elem ent not found.
Rem ov es elem ent elt fr om set s if pr esent.
Rem ov es and retur ns an arbitrar y elem ent fr om set s; raises KeyError if em pty .
Rem ov es all elem ents from this set (not on im m utable sets!).
Returns a new Set with elem ents common to all sets (in the m ethod s2 , s3 ,... can be
any iterable).
Returns a new Set with elem ents from either set (in the m ethod s2 , s3 ,... can be any
iter able).
Returns a new Set with elem ents in s1 but not in any of s2, s3 ... (in the m ethod s2 ,
s3 ,... can be any iter able)
Returns a new Set with elem ents in either s1 or s2 but not both.
Returns a shallow copy of set s.
Adds all v alues from all giv en iter ables to set s.
Named T uples
Py thon 2.6 module collections introduces the namedtuple dataty pe. The factory function namedtuple(typename, fieldnames)
creates subclasses of tuple whose fields are accessible by nam e as well as index :
# Create a named tuple class 'person':
person = collections.namedtuple('person', 'name firstName age') # field names separated by space or comma
assert issubclass(person, tuple)
assert person._fields == ('name', 'firstName', 'age')
# Create an instance of person:
jdoe = person('Doe', 'John', 30)
assert str(jdoe) == "person(name='Doe', firstName='John', age=30)"
assert jdoe[0] == jdoe.name == 'Doe' # access by index or name is equivalent
assert jdoe[2] == jdoe.age == 30
# Convert instance to dict:
assert jdoe._asdict() == {'age': 30, 'name': 'Doe', 'firstName': 'John'}
# Although tuples are normally immutable, one can change field values via _replace():
jdoe._replace(age=25, firstName='Jane')
assert str(jdoe) == "person(name='Doe', firstName='Jane', age=25)"
Date/T ime
Py thon has no intrinsic Date and Time ty pes, but prov ides 2 built-in modules:
time : time access and conv ersions
datetime : classes date , time , datetime, timedelta , tzinfo .
calendar : with functions such as isleap(year), leapdays(y1, y2) and weekday(year, month, day) .
See also the third-party module: mxDateTime .
Ad v a n ced Typ es
- See manuals for more details Module objects
Class objects
Class instance objects
Type objects (see m odule: ty pes)
File objects (see abov e)
Slice objects
S ta temen ts
St a t em en t
Resu lt
pass
del name[, name]*
print[>> fileobject,] [s1 [, s2 ]* [,]
Nu ll statem ent
Unbind name(s) fr om object. Object w ill be indirectly (and autom atically ) deleted only
if no longer r efer enced.
Writes to sy s.stdout, or to fileobject if supplied. Puts spaces between argum ents. Puts
newline at end u nless statem ent ends with comma [if nothing is printed when u sing a
com m a, try calling sys.stdout.flush() ]. Print is not r equired when running
interactiv ely , sim ply ty ping an expr ession w ill print its v alue, u nless the v alue is None.
Executes x in nam espaces prov ided. Defau lts to cur rent nam espaces. x can be a string,
open file-like object or a function object. locals can be any m apping ty pe, not only a
regu lar Py thon dict. See also built-in function execfile .
Call fu nction callable w ith param eters. Param eters can be passed by nam e or be om itted
if fu nction defines defau lt v alues. E.g. if callable is defined as "def callable(p1=1,
p2=2) "
"callable()" < = > "callable(1 , 2 )"
"callable(1 0)" < = > "callable(1 0, 2 )"
"callable(p2 = 99 )" < = > "callable(1 , 9 9)"
*args is a tu ple of positional argum ents.
**kw is a dictionary of keyword argu m ents.
See fu nction definition.
Assignment operators
Assignment operators
Oper a t or Resu l t
a=b
a += b
a -= b
a *= b
a /= b
a //= b
a %= b
a **= b
a &= b
a |= b
a ^= b
a >>= b
a <<= b
Not es
(1 )(2 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
(3 )
Notes:
(1 ) Can unpack tuples, lists, and strings:
first, second = l[0:2]
# equivalent to: first=l[0]; second=l[1]
[f, s] = range(2)
# equivalent to: f=0; s=1
c1,c2,c3 = 'abc'
# equivalent to: c1='a'; c2='b'; c3='c'
(a, b), c, (d, e, f) = ['ab', 'c', 'def']
# equivalent to: a='a'; b='b'; c='c'; d='d'; e='e'; f='f'
(3) Not ex actly equiv alent - a is ev aluated only once. Also, where possible, operation performed in-place - a is modified
rather than replaced.
Conditional Expressions (not statements) hav e been added since 2.5 [PEP 308]:
result = (whenTrue if condition else whenFalse)
if condition:
suite
[elif condition: suite]*
[else:
suite]
while condition:
suite
[else:
suite]
for element in sequence:
suite
[else:
suite]
break
continue
ret urn [result]
yield expression
Resu l t
Usu al if/else if/else statem ent. See also Conditional Expr essions for one-line if-statem ents.
Usu al w hile statem ent. The else suite is executed after loop exits, u nless the loop is exited with
break .
Iterates ov er sequence, assigning each elem ent to element. Use bu ilt-in range or xrange fu nction to
iterate a nu m ber of tim es. The else suite is executed at end u nless loop exited with break.
Also see List com pr ehensions.
Im m ediately exits for or while loop.
Im m ediately does next iter ation of for or while loop.
Exits fr om fu nction (or m ethod) and retu rns result (use a tuple to retu rn m ore than one v alu e). If
no resu lt giv en, then retur ns None .
(Only used within the body of a gener ator function, ou tside a tr y of a try..finally ). "Returns" the
ev alu ated expression.
Exception st atements
Exception statements
St a t em en t
Resu l t
print line
with threading.Lock(): # lock au tom atically released on block exit
do som ething...
When an error message is printed for an unhandled ex ception, the class name is printed, then a colon and a space, and
finally the instance conv erted to a string using the built-in function str().
A ll built-in ex ception classes deriv es from StandardError , itself deriv ed from Exception .
[PEP 352]: Ex ceptions can now be new-sty le classes, and all built-in ones are. Built-in ex ception hierarchy slightly
reorganized with the introduction of base class BaseException . Raising strings as ex ceptions is now deprecated (warning).
Resu l t
Im por ts m odu les. Mem bers of m odu le m ust be referr ed to by qualify ing with
[package.]m odule nam e, e.g.:
import sys; print sys.argv
import package1.subpackage.module
package1.subpackage.module.foo()
Nam es are fr om global scope (usually m eaning from m odu le) rather than local (u sually
Function Definition
def funcName ([paramList]) :
suite
A rgs are passed by "call-by -object-reference". This means, that mutable objects can be modified (ie. inout parameters),
while immutable are passed by v alue (ie. in parameters).
Use return to return (None ) from the function, or return value to return value. Use a tuple to return more than one
v alue, e.g. return 1,2,3
Keyword arguments arg=value specify a default value (ev aluated at function def. time). They can only appear last in the
param list, e.g. foo(x, y=1, s='') .
Pseudo-arg *args captures a tuple of all remaining non-key word args passed to the function, e.g. if def foo(x, *args):
... is called foo(1, 2, 3) , then args will contain (2,3) .
Pseudo-arg **kw args captures a dictionary of all ex tra key word arguments, e.g. if def foo(x, **kwargs): ... is called
foo(1, y=2, z=3) , then kwargs will contain {'y':2, 'z':3} . if def foo(x, *args, **kwargs): ... is called foo(1, 2,
3, y=4, z=5) , then args will contain (2, 3) , and kwargs will contain {'y':4, 'z':5}
args and kwargs are conv entional names, but other names may be used as well.
*args and **kw args can be "forwarded" (indiv idually or together) to another function, e.g.
def f1(x, *args, **kwargs):
f2(*args, **kwargs)
Ex amples:
class MyClass (class1, class2): ...
Creates a class object inheriting from both class1 and class2. A ssigns new class object to name MyClass .
class MyClass: ...
Creates a base class object (inheriting from nothing). Assigns new class object to name MyClass . Since 2.5 the equiv alent
sy ntax class MyClass(): ... is allowed.
class MyClass (object): ...
Creates a new -style class (inheriting from object makes a class a new -style class -av ailable since Py thon 2.2-). A ssigns new
class object to name MyClass .
First arg to class instance methods (operations) is alway s the target instance object, called 'self' by conv ention.
Special static method __new__(cls[,...]) called when instance is created. 1 st arg is a class, others are args to __init__(),
more details here
Special method __init__() is called when instance is created.
Special method __del__() called when no more reference to object.
Create instance by "calling" class object, possibly with arg (thus instance=apply (aClassObject, args...) creates an
instance!)
Ex ample:
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)
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 ex plicitly (see call_parent in ex ample abov e).
Many other special methods av ailable for implementing arithmetic operators, sequence, mapping index ing, etc...
Ty p e s / c la s s e s u n ific a t io n
Base ty pes int , float , str , list, tuple, dict and file now (2.2) behav e like classes deriv ed from base class object , and may
be subclassed:
x = int(2) # built-in cast function now a constructor for base type
y = 3 # <=> int(3) (litterals are instances of new base types)
print type (x), type(y) # int, int
assert isinstance(x, int) # replaces isinstance(x, types.IntType)
assert issubclass(int, object) # base types derive from base class 'object'.
s = "hello" # <=> str("hello")
assert isinstance(s, str)
f = 2.3 # <=> float(2.3)
class MyInt (int): pass
# may subclass base types
x,y = MyInt(1), MyInt("2")
print x, y, x+y # => 1,2,3
class MyList(list): pass
l = MyList("hello")
print l # ['h', 'e', 'l', 'l', 'o']
I t erat ors
A n iterator enumerates elements of a collection. It is an object with a single method next() returning the nex t element or
raising StopIteration .
Y ou get an iterator on obj v ia the new built-in function iter(obj), which calls obj.__class__.__iter__() .
A collection may be its own iterator by implementing both __iter__() and next() .
Built-in collections (lists, tuples, strings, dict) implement __iter__() ; dictionaries (maps) enumerate their key s; files
enumerates their lines.
Y ou can build a list or a tuple from an iterator, e.g. list(anIterator)
Py thon implicitly uses iterators wherev er it has to loop :
for elt in collection :
if elt in collection:
Generators
A generator is a function that retains its state between 2 calls and produces a new v alue at each inv ocation. The v alues
are returned (one at a time) using the key word yield , while return or raise StopIteration() are used to notify the end of
v alues.
A ty pical use is the production of IDs, names, or serial numbers. Fancier applications like nanothreads are also possible.
To use a generator: call the generator function to get a generator object, then call generator.next() to get the nex t
v alue until StopIteration is raised.
2.4 introduces generator expressions [PEP 289] similar to list comprehensions, ex cept that they create a generator
that will return elements one by one, which is suitable for long sequences :
linkGenerator = (link for link in get_all_links() if not link.followed)
for link in linkGenerator:
...process link...
Py thon now transparently uses descriptors to describe and access the attributes and methods of new-sty le classes (i.e.
deriv ed from object ). )
Built-in descriptors now allow to define:
Static m ethods : Use staticmethod(f) to make method f(x) static (unbound), or (recommended) use decorator
@staticmethod.
Class m ethods: like a static but takes the Class as 1 st argument => Use f = classmethod(f) to make method
f(theClass, x) a class method, or (recommended) use decorator @classmethod.
Properties : A property is an instance of the new built-in ty pe property , which implements the descriptor
protocol for attributes => Use propertyName = property(fget=None, fset=None, fdel=None, doc=None) to define
a property inside or outside a class. Then access it as propertyName or obj.propertyName.
Since 2.6, the new decorators @prop.getter , @prop.setter , and @prop.deleter add functions to an ex isting
property :
class C(object):
@property # (since Python 2.4)
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Slots. New sty le classes can define a class attribute __slots__ to constrain the list of assignable attribute names,
to av oid ty pos (which is normally not detected by Py thon and leads to the creation of new attributes), e.g.
__slots__ = ('x', 'y')
Note: According to recent discussions, the real purpose of slots seems still unclear (optimization?), and their use
should probably be discouraged.
thus, a decorator can be any function returning another function usually applied as a function transformation.
Sev eral decorators can be applied in cascade :
A decorator is just a function taking the function to be decorated and returns the same function or some new callable
thing.
Decorator functions can take arguments:
@A
@B
@C(args)
becomes :
def f(): ...
_deco = C(args)
f = A(B(_deco(f)))
The decorators @staticmethod and @classmethod replace more elegantly the equiv alent declarations f =
staticmethod(f) and f = classmethod(f) .
Misc
lambda [param_list]: returnedExpr
List comprehensions
result = [ expression for item1 in sequence1 [if condition1]
[for item2 in sequence2 ... for itemN in sequenceN]
]
Sets:
>>> {('a'*x) for x in range(6)}
set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])
automatically imported.
__import __(name[,
globals[,locals[,from list]]])
abs(x)
all(iterable)
any(iterable)
apply(f, args[, keywords])
basestring()
bin(x)
bool([x])
callable(x)
chr(i)
classmethod(function)
Resu l t
Im por ts m odu le within the giv en context (see library r eference for m ore details)
Returns the absolu te v alue of the num ber x.
Returns True if bool(x) is True for all v alues x in the iterable.
Returns True if bool(x) is True for any v alue x in the iterable.
Calls func/m ethod f with argum ents args and optional key words. Deprecat ed since 2.3,
replace apply(func, args, keywords) with func(*args, **keywords) [details]
Abstract su perclass of str and unicode; can't be called or instantiated directly , but usefu l in:
isinstance(obj, basestring) .
Conv erts a nu m ber to a binary string.
Conv erts a v alu e to a Boolean, using the standard truth testing procedure. If x is false or om itted,
r eturns False; otherw ise retur ns True . bool is also a class/ty pe, subclass of int . Class bool
cannot be subclassed further. Its only instances are False and True . See also boolean operator s
Returns a Buffer from a slice of object, which m ust su pport the bu ffer call interface (string,
ar ray , buffer). Non essential function, see [details]
Constru cts a m u table sequence of bytes . This ty pe su pports m any of the sam e operations
av ailable in strs and list s. The latter for m sets the size and initializes to all zer o by tes.
Constru cts an 8-bit str ing repr esentation of an object. Equiv alent to str for now, but this can be
u sed to explicitly indicate strings which should not be unicode when conv erting to Py thon 3 .0
[PEP3 1 1 2 ]
Returns True if x callable, else False.
Returns one-character string w hose ASCII code is integer i.
Returns a class m ethod for function. A class m ethod receiv es the class as im plicit fir st argum ent,
just like an instance m ethod r eceiv es the instance. To declar e a class m ethod, use this idiom :
class C:
def f(cls, arg1, arg2, ...): ...
f = classmethod(f)
Then call it on the class C.f() or on an instance C().f() . The instance is ignored except for its
class. If a class m ethod is called for a deriv ed class, the der iv ed class object is passed as the im plied
first argu m ent.
Since 2 .4 y ou can alternativ ely use the decorator notation:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
cmp(x,y)
coerce(x,y)
compile(string, filename, kind[,
flags[, dont_inherit]])
complex(real[, image])
delatt r(obj, name)
dict([mapping-or-sequence])
dir([object])
divmod(a,b)
enumerate(iterable[, start= 0])
eval(s[, globals[, locals]])
execfile(file[, globals[,locals]])
file(filename[,mode[,bufsize]])
filter(function,sequence)
float (x)
format(value[, format_spec])
frozenset([iterable])
(To execu te statements r ather than a single expression, u se Py thon statem ent exec or bu ilt-in
function execfile )
Execu tes a file w ithou t creating a new m odu le, u nlike import . locals can be any m apping ty pe,
not only a regu lar Py thon dict.
Opens a file and retu rns a new file object. Alias for open .
Constru cts a list fr om those elem ents of sequence for which function r eturns true. function takes
one param eter.
Conv erts a nu m ber or a string to floating point. Since 2 .6, x can be one of the strings 'nan',
'+inf', or '-inf' to repr esent respectiv ely IEEE 7 54 Not A Num ber, positiv e and negativ e
infinity . Use m odu le math functions isnan() and isinf() to check for NAN or infinity .
Form ats an object with the giv en specification (default '') by calling its __format__ m ethod.
Returns a frozenset (im m utable set) object w hose (im m u table) elem ents are taken fr om
iterable, or em pty by defau lt. See also Sets.
hex(x)
id(object)
input([prompt])
issubclass(class1, class2)
it er(obj[,sentinel])
len(obj)
list([seq])
locals()
long(x[, base])
map(function, sequence[,
sequence, ...])
next(iterator[, default])
object ()
oct(x)
open(filename [, mode='r',
[bufsize]])
ord(c)
pow(x, y [, z])
property ([fget[, fset[, fdel[,
doc]]]])
Returns integer ASCII v alue of c (a string of len 1 ). Works with Unicode char .
Returns x to pow er y [m odulo z]. See also ** operator.
Returns a proper ty attribute for new-style classes (classes deriv ing from object ). fget, fset, and
fdel are fu nctions to get the pr operty v alue, set the proper ty v alue, and delete the property ,
r espectiv ely . Ty pical use:
class
def
def
def
def
x =
C(object):
__init__(self): self.__x = None
getx(self): return self.__x
setx(self, value): self.__x = value
delx(self): del self.__x
property(getx, setx, delx, "I'm the 'x' property.")
When __future__.print_function is activ e, the print statem ent is replaced by this fu nction
[PEP3 1 05]. Each item in args is pr inted to file with sep as the delim iter, and finally follow ed by
end.
Each of these statem ents:
print 'foo', 42
print 'foo', 42,
print >> sys.stderr 'warning'
raw_input([prompt])
reduce(f, list [, init])
reload(module)
repr(object)
round(x, n= 0)
set([iterable])
setattr(object, name, value)
slice([start,] stop[, step])
sorted(iterable[, cmp[, key[,
reverse]]])
staticmethod(function)
Then call it on the class C.f() or on an instance C().f() . The instance is ignored except for its
class.
Since 2 .4 y ou can alternativ ely use the decorator notation:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
str(object)
sum(iterable[, start= 0])
super( type[, object-or-type])
Returns a str ing containing a nicely printable repr esentation of an object. Class ov er ridable
(__str __). See also repr ().
Returns the sum of a sequ ence of num bers (not strings), plus the v alu e of par am eter . Retur ns
start w hen the sequ ence is em pty .
Returns the superclass of type. If the second argum ent is om itted the super object retur ned is
u nbou nd. If the second argu m ent is an object, isinstance(obj, type) m u st be tr ue. If the
second argum ent is a ty pe, issubclass(type2, type) m ust be true. Ty pical u se:
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
tuple([seq])
type(obj)
unichr(code)
unicode(string[,
encoding[,error]]])
vars([object])
Creates an em pty tuple or a tuple with sam e elem ents as seq. seq m ay be a sequence, a container
that su pports iteration, or an iter ator object. If seq is already a tu ple, retu rns it self (not a copy ).
Returns a type object [see m odu le types] representing the ty pe of obj. Exam ple: im por t ty pes if
ty pe(x) = = ty pes.StringTy pe: pr int 'It is a string'. NB: it is better to use instead: if isinstance(x,
ty pes.StringTy pe)...
Returns a unicode string 1 char long w ith giv en code.
Creates a Unicode str ing from a 8-bit string, u sing the giv en encoding nam e and er ror treatm ent
('strict', 'ignore',or 'replace'}. For objects which prov ide a __unicode__() m ethod, it w ill call this
m ethod w ithou t argum ents to create a Unicode string.
Without ar gu m ents, r eturns a dictionar y cor responding to the cu rrent local sy m bol table. With
a m odule, class or class instance object as ar gu m ent, retur ns a dictionary corresponding to the
object's sy m bol table. Usefu l w ith the "%" string form atting oper ator.
Like range(), but doesn't actually store entire list all at once. Good to use in "for" loops when ther e
is a big range and little m em ory .
[No, that's not a com pression tool! For that, see m odule zipfile] Returns a list of tu ples w her e each
tu ple contains the nth elem ent of each of the argum ent sequences. Since 2 .4 r eturns an em pty
list if called w ith no argum ents (was r aising TypeError befor e).
KeyboardInterrupt & SystemExit were mov ed out of Exception because they don't really represent errors, so now a
try:...except Exception: will only catch errors, while a try:...except BaseException: (or simply try:..except: ) will still
UnicodeError
On Unicode-related encoding or decoding error.
UnicodeDecodeError
On Unicode decoding error.
UnicodeEncodeError
On Unicode encoding error.
UnicodeT ranslateError
On Unicode translation error.
StopIteration
Raised by an iterator's next() method to signal that there are no further v alues.
Sy stem Ex it
Mov ed under BaseException .
Warning
Base class for warnings (see module warning )
DeprecationWarning
Warning about deprecated code.
FutureWarning
Warning about a construct that will change semantically in the future.
Im portWarning
Warning about probable mistake in module import (e.g. missing __init__.py ).
Ov erflowWarning
Warning about numeric ov erflow. Won't ex ist in Py thon 2.5.
PendingDeprecationWarning
Warning about future deprecated code.
Runtim eWarning
Warning about dubious runtime behav ior.
Sy ntax Warning
Warning about dubious sy ntax .
UnicodeWarning
When attempting to compare a Unicode string and an 8-bit string that can't be conv erted to Unicode using
default ASCII encoding (raised a UnicodeDecodeError before 2.5).
UserWarning
Warning generated by user code.
__new__(cls[, ...])
__init__(self, args)
__del__(self)
__repr__(self)
__str__(self)
__sizeof__(self)
__format __(self, format_spec)
__cmp__(self,other)
__index__(self)
__lt __(self, other)
__le__(self, other)
__gt __(self, other)
__ge__(self, other)
__eq__(self, other)
__ne__(self, other)
__hash__(self)
__nonzero__(self)
__get attr__(self,name)
__get attribut e__( self, name)
__dir__( self)
Descr i pt i on
Instance creation (on constru ction). If __new__ retur ns an instance of cls then __init__ is
called w ith the rest of the argum ents (...), otherw ise __init__ is not inv oked. More details
here.
Instance initialization (on constru ction)
Called on object dem ise (r efcount becom es 0)
repr() and `...` conv ersions
str() and print statem ent
Retu rns am ount of m em ory used by object, in by tes (called by sys.getsizeof() ).
format() and str.format() conv er sions
Com pares self to other and retu rns < 0, 0, or > 0. Im plem ents > , < , = = etc...
[PEP3 57 ] Allow s u sing any object as integer indice (e.g. for slicing). Must retu rn a single
integer or long integer v alu e.
Called for self < other com parisons. Can retur n any thing, or can raise an exception.
Called for self < = other com parisons. Can retur n any thing, or can raise an exception.
Called for self > other com parisons. Can retur n any thing, or can raise an exception.
Called for self > = other com parisons. Can retur n any thing, or can raise an exception.
Called for self = = other com parisons. Can retur n any thing, or can raise an exception.
Called for self != other (and self < > other) com par isons. Can retu rn any thing, or can raise an
exception.
Com pute a 3 2 bit hash code; hash() and dictionar y ops. Since 2 .5 can also retu rn a long
integer, in w hich case the hash of that v alu e will be taken.Since 2 .6 can set __hash__ = None
to v oid class inherited hashability .
Retu rns 0 or 1 for truth v alue testing. when this m ethod is not defined, __len__() is called if
defined; otherwise all class instances are considered "tru e".
Called w hen attribu te lookup doesn't find name. See also __getattribute__.
Sam e as __getattr __ but always called w henev er the attr ibute name is accessed.
Retu rns the list of nam es of v alid attributes for the object. Called by builtin function dir(),
traceback)
None . If an er ror occur ed, they w ill contain inform ation about the class of the exception, the
exception object and a traceback object, respectiv ely . If the exception is handled pr operly ,
retu rn True. If it retu rns False , the with-block re-raises the exception.
Operat ors
See list in the operator module. Operator function names are prov ided with 2 v ariants, with or without leading & trailing '__'
(e.g. __add__ or add).
Numeric operations special methods
Oper a t or
Speci a l m et h od
self + other
self - other
self * other
self / other
self // other
self % other
divmod(self,other)
self ** other
self & other
self ^ other
self | other
self << other
self >> other
bool(self)
-self
+self
abs(self)
~self
self += other
self -= other
self *= other
self /= other
self //= other
self %= other
self **= other
self &= other
self ^= other
self |= other
self <<= other
self >>= other
__add__(self, other)
__sub__(self, other)
__mul__(self, other)
__div__(self, other) or __t ruediv __(self,other) if __future__.division is activ e.
__floordiv__(self, other)
__mod__(self, other)
__divmod__(self, other)
__pow__(self, other)
__and__(self, other)
__xor__(self, other)
__or__(self, other)
__lshift__(self, other)
__rshift __(self, other)
__nonzero__(self) (used in boolean testing)
__neg__(self)
__pos__(self)
__abs__(self)
__inv ert __(self) (bitwise)
__iadd__(self, other)
__isub__(self, other)
__imul__(self, other)
__idiv__(self, other) or __itruediv__(self,other) if __future__.division is in effect.
__ifloordiv__(self, other)
__imod__(self, other)
__ipow__(self, other)
__iand__(self, other)
__ixor__(self, other)
__ior__(self, other)
__ilshift__(self, other)
__irshift__(self, other)
Conversions
bu i lt -i n fu n ct i on
int (self)
long(self)
float (self)
complex(self)
oct(self)
hex(self)
coerce(self, other)
Specia l m et h od
__int__(self)
__long__(self)
__float__(self)
__complex__(self)
__oct __(self)
__hex__(self)
__coerce__(self, other)
Right-hand-side equiv alents for all binary operators ex ist (__radd__, __rsub__, __rmul__, __rdiv __, ...).
They are called when class instance is on r-h-s of operator:
a + 3 calls __add__(a, 3)
3 + a calls __radd__(a, 3)
Special operations for containers
Oper a t i on
Speci a l m et h od
A l l sequ en ces a n d m a ps :
Not es
len(self)
self[k]
__len__(self)
__getitem__(self, k)
self[k] = value
del self[k]
__missing__(self, key)
__setitem__(self, k, value)
__delitem__(self, k)
a slice.
Hook called when key is not found in the dictionary , r eturns the defau lt v alue.
Set elem ent at indice/key /slice k.
Delete elem ent at indice/key /slice k.
del self[k]
elt in self
elt not in self
it er(self)
__delitem__(self, k)
__contains__(self, elt)
not __contains__(self, elt)
__iter__(self)
self[i:j]
__getslice__(self, i, j)
self[i:j] = seq
__setslice__(self, i, j,seq)
del self[i:j]
__delslice__(self, i, j)
self * n
self + other
__mul__(self, n)
__add__(self, other)
hash(self)
__hash__(self)
Mea n i n g
__methods__
(list, R/O): list of m ethod nam es of the object Deprecat ed, use dir() instead
Modules
A t t r i bu t e
Mea n i n g
__doc__
__name__
__package__
__dict__
__file__
__pat h__
Classes
A t t r i bu t e
Mea n i n g
__doc__
__name__
__module__
__bases__
__dict__
Instances
A t t r i bu t e
__class__
__dict__
Mea n in g
Mea n i n g
__doc__
__name__
func_doc
func_name
func_defaults
func_code
func_globals
User-defined Methods
A t t r i bu t e
__doc__
__name__
im_class
im_self
__self__
im_func
__func__
Mea n i n g
__doc__
__name__
__self__
__members__
Mea n i n g
Codes
A t t r i bu t e
Mea n in g
co_name
co_argcount
co_nlocals
co_v arnames
co_code
co_consts
co_names
co_filename
co_firstlineno
co_lnotab
co_stacksize
co_flags
Frames
A t t r i bu t e
Mea n i n g
f_back
f_code
f_locals
f_globals
f_builtins
f_restricted
f_lineno
f_last i
f_trace
f_exc_type
f_exc_value
f_exc_traceback
Tracebacks
A t t r i bu t e
tb_next
tb_frame
tb_lineno
tb_last i
Mea n i n g
(fram e/None, R/O): next lev el in stack trace (towar d the fr am e where the exception occu rred)
(fram e, R/O): execution fram e of the curr ent lev el
(int, R/O): line nu m ber w here the exception occured
(int, R/O): precise instru ction (index into by tecode)
Slices
A t t r i bu t e Mea n i n g
start
stop
step
Complex numbers
A t t r i bu t e Mea n in g
real
imag
xranges
A t t r i bu t e Mea n in g
tolist
argv
builtin_m odule_nam es
by teor der
copy right
dont_w rite_by tecode
exec_prefix
prefix
execu table
exitfunc
flags
float_info
Con t en t
The list of com m and line argum ents passed to a Py thon scr ipt. sys.argv[0] is the script nam e.
A list of strings giv ing the nam es of all m odules w ritten in C that ar e linked into this interpreter .
Nativ e by te order , either 'big'(-endian) or 'little'(-endian).
A str ing containing the copy right pertaining to the Py thon interpreter .
If True , pr ev ents Py thon from from wr iting .py c or .py o files (sam e as inv ocation option -B).
Root director y where platfor m -dependent Py thon files are installed, e.g. 'C:\\Py thon2 3 ', '/usr'.
Nam e of executable binary of the Py thon interpreter (e.g. 'C:\\Py thon2 3 \\py thon.exe',
'/usr/bin/py thon')
User can set to a param eterless function. It will get called before interpreter exits. Deprecated since 2 .4.
Code should be using the existing atexit m odu le
Statu s of com m and line flags, as a R/O struct. [details]
A structseq holding inform ation about the float ty pe (precision, internal representation, etc...).
float_info
last_ty pe, last_v alue,
last_tr aceback
m axint
m axunicode
m odu les
path
platform
ps1 , ps2
stdin, stdou t, stderr
su bv er sion
v er sion
v er sion_info
winv er
A structseq holding inform ation about the float ty pe (precision, internal representation, etc...).
[details]
Set only when an exception not handled and inter pr eter prints an err or. Used by debu ggers.
Maxim um positiv e v alue for integers. Since 2 .2 integer s and long integers ar e unified, thu s integers
hav e no lim it.
Largest su ppor ted code point for a Unicode character.
Dictionary of m odu les that hav e alr eady been loaded.
Search path for external m odules. Can be m odified by program . sys.path[0] = = directory of script
cu rrently executed.
The cu rrent platfor m , e.g. "su nos5", "w in3 2 "
Prom pts to use in interactiv e m ode, norm ally "> > > " and "..."
File objects u sed for I/O. One can r edirect by assigning a new file object to them (or any object: w ith a
m ethod write(string) for stdout/stderr, or w ith a m ethod readline() for stdin).
__stdin__ , __stdout__ and __stderr__ are the default v alu es.
Info about Py thon bu ild v ersion in the Subv ersion r epository : tu ple (interpreter-nam e, branch-nam e,
rev ision-range), e.g. ('CPython', 'tags/r25', '51908').
String containing v ersion info abou t Py thon inter pr eter.
Tuple containing Py thon v er sion info - (major, minor, micro, level, serial).
Ver sion nu m ber u sed to for m registry key s on Windows platform s (e.g. '2 .2 ').
Resu lt
display hook
excepthook
exit(n)
getcheckinter v al() /
setcheckinter v al(interval)
getrefcount(object)
getsizeof(object[, default])
settr ace(func)
setpr ofile(func)
exc_info()
setdefaultencoding(encoding)
getrecursionlim it()
setrecu rsionlim it()
Retu rns the cur rent stack fr am es for all ru nning threads, as a dictionary m apping thread
identifiers to the topm ost stack fram e curr ently activ e in that thr ead at the tim e the fu nction
is called.
The function used to display the output of com m ands issu ed in interactiv e m ode - defaults to
the builtin repr() . __displayhook__ is the original v alue.
Can be set to a u ser defined function, to which any uncau ght exceptions are passed.
__excepthook__ is the original v alu e.
Exits w ith status n (usually 0 m eans OK). Raises SystemExit exception (hence can be caught
and ignor ed by progr am )
Gets / Sets the interpreter's thread sw itching interv al (in num ber of by tecode instructions,
default: 1 0 until 2 .2 , 1 00 from 2 .3 ).
Retu rns the reference count of the object. Gener ally 1 higher than y ou m ight expect, because
of object arg tem p reference.
Retu rns the am ou nt of m em ory used by object, in by tes. Calls o.__sizeof__() if av ailable.
default r eturned if size can't be determ ined. [details]
Sets a tr ace function: called befor e each line of code is exited.
Sets a pr ofile function for perfor m ance profiling.
Info on exception cur rently being handled; this is a tuple (exc_ty pe, exc_v alu e,
exc_tr aceback). Warning: assigning the tr aceback retur n v alue to a local v ariable in a
function handling an exception will cause a circu lar reference.
Change default Unicode encoding - defaults to 7 -bit ASCII.
Retr iev e m axim u m recur sion depth.
Set m axim u m recur sion depth (defau lt 1 000).
os
Miscellaneous operating sy stem interfaces. Many functions, see the for a comprehensiv e list!
"sy nony m" for whatev er OS-specific module (nt, mac, posix ...) is proper for current env ironment. This module uses posix
whenev er possible.
See also M.A. Lemburg's utility platform.py (now included in 2.3+).
Some os variables
V a r i a bl e Mea n i n g
nam e
path
cur dir
par dir
sep
altsep
pathsep
linesep
Some os functions
Fu n ct i on
posix
Posix OS interfaces.
Resu l t
Recur siv e directory cr eation (create r equir ed interm ediary dir s); os.error if fails.
Recur siv e directory delete (delete interm ediary empty dir s); fails ( os.error) if the
directories are not em pty .
Recur siv e directory or file renam ing; os.error if fails.
Retu rns a string containing n by tes of random data.
Posix OS interfaces.
Do not im port this m odule directly , im port os instead ! (see also module: shutil for file copy & remov e functions)
posix Variables
V a r i a bl e Mea n i n g
env iron
err or
Resu l t
access(path, mode)
Retu rns Tr ue if the requ ested access to path is granted. Use mode= F_OK to check for existence, or an
OR-ed com bination of R_OK , W_OK , and X_OK to check for r, w , x per m issions.
Changes cur rent directory to path.
Changes the m ode of path to the num er ic mode
Closes file descriptor fd opened with posix.open.
Im m ediate exit, w ith no cleanups, no Sy stem Exit, etc... Should use this to exit a child process.
"Becom e" executable p w ith args args
Retu rns a string r epresenting the cur rent working directory .
Retu rns a Unicode string r epresenting the cur rent w orking directory .
Retu rns the cu rrent process id.
chdir (path)
chm od(path, mode)
close(fd)
_exit(n)
execv (p, args)
getcwd()
getcwdu ()
getpid()
getsid()
for k()
kill(pid, signal)
listdir(path)
lseek(fd, pos, how)
m kdir (path[, mode])
open(file, flags, mode)
pipe()
popen(command, mode= 'r',
bufSize= 0)
rem ov e(path)
renam e(old, new )
renam es(old, new)
rm dir(path)
read(fd, n)
stat(path)
sy stem (command)
tim es()
unlink(path)
utim e(path, (aTime, mTime))
wait()
waitpid(pid, options)
walk(top[, topdown= Tru e [,
onerror= None[,
followlinks= False]]])
wr ite(fd, str)
posixpath
Posix pathname operations.
Do not im port this m odule directly , im port os instead and refer to this module as os.path. (e.g. os.path.exists(p) )!
posixpath functions
Fu n ct i on
abspath(path)
com m onprefix(list)
dirnam e/basenam e(path)
exists(path)
expanduser (path)
expandv ars(path)
getatim e(path)
getctim e(path)
Resu lt
Retu rns absolute path for path, taking cur rent working dir in account.
Retu rns the longu est path prefix (taken character -by -character ) that is a pr efix of all paths in list (or ''
if list em pty ).
directory and nam e parts of path. See also split.
Tru e if path is the path of an existing file or directory . See also lexists .
Retu rns a copy of path w ith "~" expansion done.
Retu rns string that is (a copy of) path w ith env ironm ent v ars $name or ${name} expanded. [Window s:
case significant; m ust use Unix: $ v ar notation, not %v ar %; 2 .6: Notation %name% also supported.]
Retu rns last access tim e of path (integer nb of seconds since epoch).
Retu rns the m etadata change tim e of path (integer nb of seconds since epoch).
getctim e(path)
getm tim e(path)
getsize(path)
isabs(path)
isdir(path)
isfile(path)
islink(path)
ism ount(path)
join(p[,q[,...]])
lexists(path)
nor m case(path)
nor m path(path)
realpath(path)
relpath(path[, start])
sam efile(f1, f2)
sam eopenfile(f1, f2)
sam estat(s1, s2)
split(p)
splitdr iv e(p)
splitext(p)
walk(p, visit, arg)
Retu rns the m etadata change tim e of path (integer nb of seconds since epoch).
Retu rns last m odification tim e of path (integer nb of seconds since epoch).
Retu rns the size in by tes of path. os.error if file inexistent or inaccessible.
Tru e if path is absolute.
Tru e if path is a dir ectory .
Tru e if path is a regular file.
Tru e if path is a sy m bolic link.
Tru e if path is a m ount point [tru e for all dirs on Window s].
Joins one or m ore path com ponents in a w ay suitable for the current OS.
Tru e if the file specified by path exists, whether or not it's a sy m bolic link (u nlike exists).
Norm alizes case of path. Has no effect u nder Posix.
Norm alizes path, elim inating dou ble slashes, etc...
Retu rns the canonical path for path, elim inating any sy m bolic links encountered in the path.
Retu rns a relativ e filepath to path, from the cur rent directory by defau lt, or from start if specified.
Tru e if the 2 paths f1 and f2 reference the sam e file.
Tru e if the 2 open file objects f1 and f2 r eference the sam e file.
Tru e if the 2 stat bu ffers s1 and s2 reference the sam e file.
Splits p into (head, tail) where tail is last pathnam e com ponent and head is ev ery thing leading u p to
that. < = > (dirname(p), basename(p))
Splits path p in a pair ('driv e:', tail) [Windows]
Splits into (root, ext) where last com p of root contains no per iods and ext is em pty or starts w ith a
period. 2 .6: Do not split on leading period.
Calls the function visit with argum ents (arg, dirname, names) for each director y recursiv ely in the
directory tree r ooted at p (inclu ding p itself if it's a dir). The ar gum ent dirname specifies the v isited
directory , the argu m ent names lists the files in the directory . The visit function m ay m odify names to
influence the set of directories v isited below dirname, e.g. to av oid v isiting certain par ts of the tree. See
also os.walk() for an alter nativ e.
shutil
High-lev el file operations (copy ing, deleting).
Main shutil functions
Fu n ct i on
Resu l t
Copies the contents of file src to file dest, r etaining file perm issions.
Recur siv ely copies an entir e director y tree rooted at src into dest (which should not
already exist). If symlinks is tru e, links in src are kept as such in dest.
2 .6: New ignore callable argum ent. Will be called with each directory path and a list of
the directory 's contents, m u st retu rn a list of nam es to ignore.
shutil.ignore_patterns() can be used to exclude glob-sty le patterns, e.g.:
shutil.copytree('projects/myProjUnderSvn', 'exportDir',
ignore=shutil.ignore_patterns('*~', '.svn'))
m ov e(src, dest)
rm tr ee(path [, ignore_errors
[, onerror]])
m ake_archiv e(base_name, format
[, root_dir [, base_dir [, verbose
[, dry_run [, owner [, group
[, logger]]]]]]])
time
Time access and conv ersions.
(see also module mx DateTime if y ou need a more sophisticated date/time management)
Variables
V a r i a bl e Mea n in g
altzone
day light
tim ezone
tznam e
Signed offset of local DST tim ezone in sec w est of the 0th m eridian.
Non zer o if a DST tim ezone is specified.
The offset of the local (non-DST) tim ezone, in seconds w est of UTC.
A tuple (nam e of local non-DST tim ezone, nam e of local DST tim ezone).
Some functions
Fu n ct i on
Resu l t
clock()
On Unix: cu rrent pr ocessor tim e as a floating point nu m ber expr essed in seconds.
time()
gm tim e([secs]),
On Window s: w all-clock seconds elapsed since the 1 st call to this function, as a floating point
nu m ber (precision < 1 s).
Retu rns a float r epresenting UTC tim e in seconds since the epoch.
Retu rns a 9 -tuple repr esenting tim e. Cu rrent tim e is u sed if secs is not prov ided.
localtime([secs])
Since 2 .2 , r eturns a struct_time object (still accessible as a tu ple) w ith the follow ing attribu tes:
In dex A t t r ibu t e V a l u es
asctim e([timeTuple]),
ctim e([secs])
m ktim e(timeTuple)
strftime(format[, timeTuple])
strptime(string[, format])
sleep(secs)
0
1
2
3
4
5
tm _y ear
tm _m on
tm _m day
tm _hou r
tm _m in
tm _sec
6
7
8
tm _wday
tm _y day
tm _isdst
2 4 -char acter str ing of the follow ing form : 'Mon Apr 03 08:3 1 :1 4 2 006'. timeTuple defaults to
localtime() if om itted.
equ iv alent to asctime(localtime(secs))
Inv er se of localtime (). Returns a float representing a num ber of seconds.
Formats a tim e tuple as a string, accor ding to format (see table below). Cur rent tim e is u sed if
timeTuple is om itted.
Parses a string repr esenting a tim e according to format (sam e form at as for strftime() , see
below), default "%a %b %d %H:%M:%S %Y" = asctim e form at.
Retu rns a tim e tuple/ struct_time .
Suspends execu tion for secs seconds. secs can be a float.
st ring
Common string operations.
As of Py thon 2.0, much (though not all) of the functionality prov ided by the string module hav e been superseded by built-in
string methods.
Since 2.5 (?) all string module m ethods are considered deprecated => use built-in string methods instead.
Some string constant
Con st a n t
digits
hexdigits, octdigits
letters, upper case, low ercase, w hitespace
ascii_letters, ascii_lower case,
ascii_u ppercase
Mea n i n g
expandtabs(s, tabSize)
find/rfind(s, sub[, start= 0[, end= 0])
lju st/r just/center(s, width[, fillChar= ' '])
low er/upper(s)
Resu l t
low er/upper(s)
split(s[, sep=w hitespace[, maxsplit= 0]])
rsplit(s[, sep= whitespace[, maxsplit= 0]])
Concatenates a list or tuple of wor ds with interv ening separator s; inv er se of split .
Returns a copy of string s with all occu rrences of substr ing old replaced by new. Lim its
to maxsplit first substitutions if specified.
Returns a string that is (a copy of) s without leading and tr ailing chars (default:
w hitespace), if any . Also: lstrip, rstrip.
re ( sre)
Regular ex pression operations.
Handles Unicode strings. Implemented in new module sre, re now a mere front-end for compatibility .
Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*' ) to literalize backslashes.
Regular expression syntax
For m
Descr i pt i on
.
^
$
*
+
?
*?, + ?, ??
{m ,n}
{m ,n}?
[]
[^ ]
\
\\
|
(...)
(?:...)
(?
P< name>...)
(?P= name)
(?= ...)
(?!...)
(?< = ...)
(?< !...)
(?
(group)A|B)
(?#...)
(?letters)
Special sequences
Sequ en ce Descr i pt i on
Matches content of the group of the sam e nu m ber ; gr oups are nu m ber ed starting from 1 .
Matches only at the star t of the string.
Em pty str at beginning or end of word: '\bis\b' m atches 'is', bu t not 'his'.
Em pty str NOT at beginning or end of w ord.
Any decim al digit (< = > [0-9 ]).
Any non-decim al digit char (< = > [^0-9 ]).
Any w hitespace char (< = > [ \t\n\r\f\v ]).
Any non-whitespace char (<= > [^ \t\n\r\f\v ]).
Any alphaNum eric char (depends on LOCALE flag).
Any non-alphaNu m er ic char (depends on LOCALE flag).
Matches only at the end of the string.
\number
\A
\b
\B
\d
\D
\s
\S
\w
\W
\Z
Variables
V a r i a bl e Mea n i n g
err or
Functions
Fu n ct i on
Resu lt
Retu rns (a copy of) string with all non-alphanum erics backslashed.
If 0 or m ore chars at beginning of string m atches the RE patter n str ing, retur ns a
cor responding MatchObject instance, or None if no m atch.
Scans thru string for a location m atching pattern, retu rns a corresponding MatchObject
instance, or None if no m atch.
Splits string by occur rences of pattern. If captu ring () are u sed in pattern, then
occurr ences of patterns or subpatterns are also retur ned.
Retu rns a list of non-ov erlapping m atches of pattern in string, either a list of groups or a
list of tu ples if the pattern has m ore than 1 gr oup.
Retu rns an iterator ov er all non-ov erlapping m atches of pattern in string. For each m atch,
the iterator r eturns a match object. Em pty m atches are inclu ded in the r esult unless they
touch the beginning of another m atch.
Retu rns str ing obtained by replacing the (count fir st) leftm ost non-ov erlapping
occurr ences of pattern (a string or a RE object) in string by repl; repl can be a string or a
function called with a single MatchObj arg, which m ust retu rn the r eplacem ent str ing.
Sam e as sub() , bu t retu rns a tuple (newString, num berOfSu bsMade).
escape(string)
m atch(pattern, string[, flags])
search(pattern, string[, flags])
split(pattern, string[, maxsplit= 0
[, flags= 0]])
findall(pattern, string)
finditer(pattern, string[, flags])
flags
grou pindex
patter n
Descr i pt ion
Flags arg used when RE obj w as com piled, or 0 if none prov ided.
Dictionary of {grou p nam e: group num ber} in pattern.
Pattern str ing from which RE obj was com piled.
re object methods
Met h od
Resu l t
If zero or m ore char acters at the beginning of str ing m atch this regu lar expression, r etur ns a
corresponding MatchObject instance. Returns None if the string does not m atch the pattern;
note that this is different fr om a zero-length m atch.
The optional second par am eter pos giv es an index in the string w here the search is to start; it
defau lts to 0. This is not com pletely equiv alent to slicing the string; the '' pattern char acter
m atches at the real beginning of the string and at positions just after a new line, bu t not
necessarily at the index where the sear ch is to start.
The optional param eter endpos lim its how far the string will be searched; it w ill be as if the
string is endpos characters long, so only the character s fr om pos to endpos w ill be sear ched for a
m atch.
Scans through str ing looking for a location w her e this r egular expression produces a m atch, and
retu rns a corr esponding MatchObject instance. Retur ns None if no position in the string
m atches the pattern; note that this is differ ent from finding a zero-length m atch at som e point
in the string.
The optional pos and endpos param eters hav e the sam e m eaning as for the match() m ethod.
Identical to the split() fu nction, using the com piled pattern.
Identical to the findall() function, u sing the com piled patter n.
Identical to the finditer() function, u sing the com piled pattern.
Identical to the sub() function, using the com piled pattern.
Identical to the subn() fu nction, using the com piled pattern.
Mat ch Objects
Match objects are returned by the match & search functions.
Match object attributes
A t t r i bu t e Descr ipt i on
pos
endpos
re
str ing
Value of pos passed to search or m atch functions; index into string at which RE engine started sear ch.
Value of endpos passed to search or m atch fu nctions; index into str ing bey ond which RE engine w on't go.
RE object w hose m atch or search function produ ced this MatchObj instance.
Str ing passed to match() or search() .
Resu lt
Retu rns one or m or e grou ps of the m atch. If one arg, result is a string; if m ultiple args, resu lt is a tuple
Retu rns one or m or e grou ps of the m atch. If one arg, result is a string; if m ultiple args, resu lt is a tuple
with one item per ar g. If gi is 0, r eturns the entire m atching str ing; if 1 < = gi < = 99, r eturns string
m atching grou p #gi (or None if no such gr oup); gi m ay also be a group name.
Retu rns a tuple of all groups of the m atch; groups not participating to the m atch hav e a v alue of None.
Retu rns a string instead of tuple if len(tu ple)= = 1 .
Retu rns indices of start & end of substring m atched by grou p (or None if group exists bu t didn't contribute
to the m atch).
Retu rns the 2 -tu ple (start(group), end(grou p)); can be (None, None) if grou p didn't contibute to the
m atch.
grou ps()
start(group),
end(group)
span(group)
which results in
[('INTEGER', '45'),
('IDENTIFIER', 'pigeons'),
('PUNCTUATION', ','),
('INTEGER', '23'),
('IDENTIFIER', 'cows'),
('PUNCTUATION', ','),
('INTEGER', '11'),
('IDENTIFIER', 'spiders'),
('PUNCTUATION', '.')]
math
For complex number functions, see module cmath. For intensiv e number crunching, see Numerical Py thon and the Py thon and
Scientific computing page.
Constants
Na m e
pi
e
V alue
Functions
Na m e
acos(x)
acosh(x)
asin(x)
asinh(x)
atan(x)
atan2 (y, x)
atanh(x)
ceil(x)
copy sign(x, y)
cos(x)
cosh(x)
degrees(x)
erf(x)
erfc(x)
exp(x)
exm p1 (x)
fabs(x)
factorial(n)
floor(x)
fm od(x, y)
frexp(x)
fsum (iterable)
gam m a(x)
hy pot(x, y)
isinf(x)
isnan(x)
ldexp(x, i)
lgam m a(x)
Resu l t
lgam m a(x)
log(x[, base])
log1 0(x)
log1 p(x)
m odf(x)
pow(x, y)
radians(x)
sin(x)
sinh(x)
sqr t(x)
tan(x)
tanh(x)
tr unc(x)
Return the natu ral logarithm of the absolute v alu e of the Gam m a function at x.
Returns the logar ithm of x to the giv en base. If the base is not specified, retur ns the natural logarithm (base e)
of x.
Returns the base 1 0 logarithm of x.
Returns the natu ral logarithm of 1 +x (base e). The resu lt is com puted in a way which is accu rate for x near
zer o.
Returns the fr actional and integer parts of x. Both r esults carry the sign of x. The integer par t is retur ned as a
float.
Returns x**y (x to the power of y). Note that for y= 2 , it is m or e efficient to use x*x .
Conv erts angle x from degrees to r adians.
Returns the sine (m easured in r adians) of x.
Returns the hy perbolic sine of x.
Returns the square r oot of x.
Returns the tangent (m easu red in radians) of x.
Returns the hy perbolic tangent of x.
Returns the Real v alue x truncated to an Integral . Delegates to x.__trunc__() .
Compressions
Py thon contains sev eral modules for working with compressed files. The builtin function zip does not hav e any thing to do with
zipping, think instead of a zipper.
There are three different concepts with compressions:
compression of data
compression of a single file (e.g. gzip, bz2)
compression of archiv es, ie. zip-files with multple files
Compression of data
Modu l e Descr i pt i on
zlib
bz2
Com pr ession and decom pression of data (strings), using the zlib library .
Sequ ential com pression and decom pression using classes BZ2Compressor and BZ2Decompressor , or One-shot
(de)com pression though fu nctions compress() and decompress().
gzip
bz2
Read and w rite gzip-com pressed files as were they norm al files, using the GzipFile class.
Read and w rite bz2 -com pressed files as w ere they nor m al files, u sing the BZ2File class.
Compression of archives
Modu l e Descr i pt i on
zipfile
tar file
shutil
__bu iltin__
__futur e__
__m ain__
Resu l t
Pr ov ide dir ect access to all `bu ilt-in' identifiers of Py thon, e.g. __builtin__.open is the fu ll nam e
for the built-in function open().
Fu ture statem ent definitions. Used to progressiv ely intr oduce new featu res in the langu age.
Represent the (otherw ise anony m ous) scope in which the interpreter's m ain progr am execu tes -com m ands read either from standard inpu t, fr om a script file, or from an interactiv e pr om pt.
Ty pical idiom to check if a code w as ru n as a script (as opposed to being imported):
if __name__ == '__main__':
main() # (this code was run as script)
abc
aifc
any dbm
argpar se
array
ast
asy nchat
asy ncore
atexit
audiodev
audioop
(new in 2 .6) Abstract Base Classes (ABC) [PEP 3 1 1 9 ]. Equ iv alent of Jav a interfaces. The m odu le
collections defines inter faces/ABCs for m any behav iors/protocols/data stru ctures ( Iterable ,
Hashable , Sequence , Set , etc...).
Stu ff to parse AIFF-C and AIFF files.
Generic interface to all dbm clones. (dbhash, gdbm , dbm , du m bdbm ).
Par ser for com m and-line options, argum ents and su b-com m ands. For m ore C-like com m and-line
pr ocessing, see getopt.
Efficient arr ay s of num eric v alues.
(new in 2 .6) Helpers to process Trees of the Py thon Abstract Sy ntax gram m ar.
A class su pporting chat-sty le (com m and/response) pr otocols.
Basic infr astru ctur e for asy nchronou s socket serv ice clients and serv ers.
Register fu nctions to be called at exit of Py thon inter preter .
Classes for m anipu lating audio dev ices (curr ently only for Su n and SGI). Depr ecated since 2 .6.
Manipulate raw au dio data. 2 .5: Supports the a-LAW encoding.
audioop
base6 4
BaseHTTPSer v er
Bastion
bdb
binascii
binhex
bisect
bsddb
bz2
calendar
cgi
CGIHTTPServ er
cgitb
chu nk
cm ath
cm d
cm p
cm pcache
code
codecs
codeop
collections
colorsy s
com m ands
com pileall
ConfigParser
contextlib
Cookie
copy
copy _reg
cPickle
cProfile
cry pt
cStringIO
csv
cty pes
cur ses
datetim e
dbhash
decim al
difflib
dircache
dircm p
dis
distu tils
distu tils.com m and.register
distu tils.debug
distu tils.em xccom piler
distu tils.log
distu tils.sy sconfig
dl
doctest
DocXMLRPCServ er
dospath
dum bdbm
dum p
dum m y _thread
dum m y _threading
em ail
encodings
err no
err no
exceptions
fcntl
filecm p
fileinput
find
fnm atch
for m atter
fpectl
fpfor m at
fractions
ftplib
functools
futur e_bu iltins
Standard err no sy stem sy m bols. The v alue of each sy m bol is the corresponding integer v alue.
Class based built-in exception hier ar chy .
The fcntl() and ioctl() sy stem calls [Unix].
File and director y com parison.
Helper class to quickly write a loop ov er all standard inpu t files. 2 .5: Made m or e flexible (Unicode
filenam es, mode param eter, etc...)
Find files directory hierarchy m atching a pattern.
Filenam e m atching with shell patterns.
Generic ou tpu t for m atting.
Floating point exception contr ol [Unix].
General floating point for m atting functions. Depr ecated since 2 .6.
(new in 2 .6) Rational Num bers.
An FTP client class. Based on RFC 959 .
Tools for functional-sty le program m ing. See in particular function partial() [PEP3 09].
(new in 2 .6) Py thon 3 bu iltins. Prov ides functions that exist in 2 .x, but hav e different behav ior in
Py thon 3 (ascii, m ap, filter, hex...). To w rite Py thon 3 com patible code, im port the functions from
this m odule, e.g.:
from future_builtins im por t m ap
...code u sing Py thon3 -sy le m ap()...
gc
gdbm
getopt
getpass
gettext
glob
gopher lib
grp
grep
gzip
hashlib
heapq
hm ac
hotshot.stones
htm lentity defs
htm llib
HTMLParser
httplib
idlelib
ihooks
im ageop
im aplib
im ghdr
im p
im pu til
Perform garbage collection, obtain GC debu g stats, and tu ne GC param eters. 2 .5: New get_count()
function. gc.collect() takes a new generation ar gu m ent.
GNU's r einterpretation of dbm [Unix].
Standard com m and line processing in C getopt() sty le. See also argparse.
Utilities to get a passw ord and/or the cur rent user nam e.
Inter nationalization and localization support.
Filenam e "globbing" u tility .
Gopher protocol client interface.
The group database [Unix].
'grep' utilities.
Read & w rite gzipped files.
Secur e hashes and m essage digests.
Heap queu e (priority queue) helpers. 2 .5: nsmallest() and nlargest() takes a key key word
par am .
HMAC (Key ed-Hashing for Message Authentication).
Helper to r un the py stone benchm ark under the Hotshot profiler .
HTML character entity r efer ences.
HTML2 parsing u tilities. Deprecated since 2 .6 ; see HTMLParser-class.
Sim ple HTML and XHTML par ser.
HTTP1 client class.
(package) Su pport library for the IDLE dev elopm ent env ironm ent.
Hooks into the "im por t" m echanism . Depr ecated since 2 .6.
Manipulate raw im age data. Deprecated since 2 .6 ; r em ov ed in Py thon 3 .
IMAP4 client.Based on RFC 2 060.
Recognizing im age files based on their fir st few by tes.
Access the im port internals.
Pr ov ides a way of w riting cu stom ized im port hooks.
inspect
io
itertools
Tools to work w ith iterator s and lazy sequ ences. 2 .5: islice() accepts None for start & step args.
2 .6 : Sev er al new fu nctions: izip_longest , product , combinations , permutations .
(new in 2 .6) JSON (Jav aScr ipt Object Notation) interchange for m at su pport.
List of Py thon key w ords.
A Py thon re-im plem entation of hierarchical m odule im por t.
Cache lines from files.
Linux /dev /audio suppor t. Replaced by ossaudiodev (Linu x).
Su pport for nu m ber form atting u sing the curr ent locale settings. 2 .5: format() m odified; new
functions format_string() and currency()
(package) Tools for stru ctured logging in log4j sty le.
Pathnam e (or related) oper ations for the Macintosh [Mac].
Mac specific m odule for conv er sion between pathnam es and URLs [Mac].
Classes to handle Unix sty le, MMDF sty le, and MH sty le m ailboxes. 2 .5: added capability to m odify
m ailboxes in addition to reading them .
Mailcap file handling (RFC 1 52 4).
Inter nal Py thon object serialization.
Shared su pport for scanning docu m ent ty pe declarations in HTML and XHTML.
Mathem atical fu nctions. See also cm ath
MD5 m essage digest algorithm . 2 .5: Now a m ere w rapper arou nd new library hashlib .
Deprecated since 2 .6, u se hashlib m odule instead.
MH (m ailbox) inter face. Deprecated since 2 .6.
Var iou s tools used by MIME-r eading or MIME-wr iting program s. Depr ecated since 2 .6.
Guess the MIME ty pe of a file.
Generic MIME w riter . Deprecat ed since 2 .3 , use email package instead.
Mim ification and u nm im ification of m ail m essages. Deprecated since 2 .6 , u se email package
instead.
Inter face to m em or y -m apped files - they behav e like m utable str ings.
json
key w ord
knee
linecache
linuxaudiodev
locale
logging
m acpath
m acu rl2 path
m ailbox
m ailcap
m arshal
m arku pbase
m ath
m d5
m hlib
m im etools
m im ety pes
Mim eWr iter
m im ify
m m ap
m m ap
m odu lefinder
m silib
m sv crt
m u ltifile
m u ltiprocessing
m u tex
netrc
new
nis
nntplib
ntpath
ntur l2 path
nu m ber s
olddifflib
operator
optpar se
os
os.path
os2 em xpath
packm ail
par ser
pdb
pickle
pickletools
pipes
pkgu til
platform
poly
popen2
poplib
posix
posixpath
ppr int
pre
profile
pstats
pty
pwd
py _com pile
py clbr
py doc
py expat
Py Unit
Queu e
quopri
rand
random
re
readline
reconv ert
regexp
regex_sy ntax
regsub
repr
resou rce
rexec
rfc82 2
rgbim g
rlcom pleter
robotparser
sched
select
sets
sgm llib
sha
Inter face to m em or y -m apped files - they behav e like m utable str ings.
Tools to find w hat m odules a giv en Py thon progr am uses, without actually ru nning the program .
Read and w rite Microsoft Installer files [Windows].
File & Console Windows-specific oper ations [Windows].
A readline()-sty le interface to the parts of a m u ltipart m essage. Deprecated since 2 .6.
(new in 2 .6) Process-based "threading" interface. Allows to fu lly lev er age multiple processors on
a m achine [Windows, Unix] [PEP 3 7 1 ].
Mutual exclu sion -- for use with m odule sched. See also std m odu le threading , and glock.
Par ses and encapsu lates the netr c file form at.
Creation of ru ntim e internal objects (interface to interpreter object creation functions). Deprecated
since 2 .6.
Inter face to Su n's NIS (Yellow Pages) [Unix]. 2 .5: New domain arg to nis.match() and
nis.maps() .
An NNTP client class. Based on RFC 9 7 7 .
Com m on oper ations on Windows pathnam es [Windows].
Conv er t a NT pathnam e to a file URL and v ice v er sa [Windows].
Numeric Abstract Base Classes (ABC) [PEP 3 1 4 1 ]. Define a ty pe hier ar chy for nu m ber s:
Number , Complex, Real , Rational , Integral .
Old v ersion of difflib (helpers for com puting deltas betw een objects)?
Standard oper ator s as functions. 2 .5: itemgetter() and attrgetter() now suppor ts m u ltiple
fields.
Im pr ov ed com m and-line option parsing librar y (see also getopt). 2 .5: Updated to Optik library 1 .51 .
OS routines for Mac, DOS, NT, or Posix depending on w hat sy stem we're on. 2 .5: os.stat() retur n
tim e v alu es as floats; new constants to os.lseek(); new fu nctions wait3() and wait4(); on
Fr eeBSD, os.stat() retur ns tim es with nanosecond r esolu tion.
Com m on pathnam e m anipu lations.
os.path suppor t for OS/2 EMX.
Create a self-u npacking shell archiv e.
Access Py thon parse trees.
A Py thon debugger .
Pickling (sav e/ser ialize and r estore/deserialize) of Py thon objects (a faster C im plem entation exists
in built-in m odu le: cPickle ). 2 .5: Value retu rned by __reduce__() m u st be differ ent from None .
Tools to analy ze and disassem ble pickles.
Conv er sion pipeline tem plates [Unix].
Tools to extend the m odule search path for a giv en package. 2 .5: PEP3 02 's im por t hooks suppor t;
wor ks for packages in ZIP form at archiv es.
Get info about the underly ing platform .
Poly nom ials.
Spaw n a com m and with pipes to its stdin, stdout, and optionally stder r. Superseded by m odule
su bpr ocess since 2 .4. Deprecated since 2 .6.
A POP3 client class.
Most com m on POSIX sy stem calls [Unix].
Com m on oper ations on POSIX pathnam es.
Su pport to pretty -print lists, tuples, & dictionaries recursiv ely .
Su pport for regu lar expressions (RE) - see re.
Class for pr ofiling py thon code. 2 .5: See also new fast C im plem entation cProfile
Class for pr inting reports on pr ofiled py thon code. 2 .5: new stream arg to Stats constr uctor .
Pseu do term inal utilities [Linux, IRIX].
The passw or d database [Unix].
Rou tine to "com pile" a .py file to a .py c file.
Par se a Py thon file and retriev e classes and m ethods.
Generate Py thon docu m entation in HTML or text for interactiv e use.
Inter face to the Expat XML parser . 2 .5: now uses V2 .0 of the expat parser .
Unit test fram ework inspired by JUnit. See unittest .
A m ulti-pr oducer, m u lti-consum er queue. 2 .6: New queu e v ariants PriorityQueue and
LifoQueue .
Conv er sions to/from quoted-pr intable transport encoding as per RFC 1 52 1 .
Don't use unless y ou want com patibility with C's r and().
Random v ariable generators.
Regu lar Expressions.
GNU readline inter face [Unix].
Conv er t old ("regex") regular expressions to new sy ntax ("r e").
Backwar d com patibility for m odu le "regexp" u sing "regex".
Flags for regex.set_syntax().
Regexp-based split and replace u sing the obsolete regex m odule.
Alternate repr() im plem entation.
Resou rce u sage inform ation [Unix].
Restricted execution facilities ("safe" exec, ev al, etc).
Par se RFC-82 2 2 m ail header s.
Read and w rite 'SGI RGB' files.
Wor d com pletion for GNU r eadline 2 .0 [Unix]. 2 .5: Doesn't depend on readline any m ore; now
works on non-Unix platforms.
Par se r obot.txt files, u seful for web spiders.
A generally usefu l ev ent scheduler class.
Waiting for I/O com pletion.
A Set dataty pe im plem entation based on dictionar ies. Deprecated since 2 .6 , u se bu ilt-in ty pes set
and frozenset instead.
A parser for SGML, using the der iv ed class as a static DTD.
SHA-1 m essage digest algorithm . 2 .5: Now a m ere wr apper around new librar y hashlib.
sha
shelv e
shlex
shutil
signal
Sim pleHTTPServ er
Sim pleXMLRPCSer v er
site
sm tpd
sm tplib
sndhdr
socket
SocketServ er
spw d
sqlite3
sr e
stat
statv fs
str ing
Str ingIO
str ingprep
str uct
su bprocess
su nau
su nau dio
sy m bol
sy m table
sy s
sy sconfig
sy slog
tabnanny
tar file
telnetlib
tem pfile
term ios
test
textw rap
thread
threading
threading_api
tim e
tim eit
Tix
Tkinter
toaiff
token
tokenize
tr ace
tr aceback
tty
tu rtle
ty pes
tzparse
unicodedata
unittest
urllib
urllib2
urlpar se
user
UserDict
UserList
UserString
SHA-1 m essage digest algorithm . 2 .5: Now a m ere wr apper around new librar y hashlib.
Deprecated since 2 .6, u se hashlib instead.
Manage shelv es of pickled objects.
Lexical analy zer class for sim ple shell-like sy ntaxes.
Utility functions for copy ing files and dir ectory tr ees.
Set handlers for asy nchr onou s ev ents.
Sim ple HTTP Serv er.
Sim ple XML-RPC Serv er. 2 .5: New attr ibute rpc_paths .
Append m odu le search paths for third-party packages to sys.path .
An RFC 2 82 1 SMTP ser v er .
SMTP/ESMTP client class.
Sev er al r outines that help recognizing sound.
Socket operations and som e r elated functions. Now supports tim eouts thr u function
settimeout(t) . Also suppor ts SSL on Windows. 2 .5: Now supports AF_NETLINK sockets on Linux;
new socket m ethods recv_buf(buffer) , recvfrom_buf(buffer) , getfamily() , gettype() and
getproto() .
Generic socket serv er classes.
Access to the UNIX shadow password database [Unix].
DB-API 2 .0 interface for SQLite databases.
Su pport for regu lar expressions (RE). See re.
Constants/fu nctions for inter preting resu lts of os.
Constants for interpreting statv fs struct as r eturned by os.statvfs() and os.fstatvfs() (if they
exist). Deprecated since 2 .6 .
A collection of string oper ations (see Strings).
File-like objects that read/w rite a string bu ffer (a faster C im plem entation exists in built-in m odu le
cStr ingIO).
Nor m alization and m anipulation of Unicode strings.
Perform conv ersions between Py thon v alues and C str ucts represented as Py thon strings. 2 .5: faster
(new pack() and unpack() m ethods); pack and unpack to and fr om buffer objects v ia m ethods
pack_into and unpack_from .
Su bprocess m anagem ent. Replacem ent for os.sy stem , os.spawn*, os.popen*, popen2 .* [PEP3 2 4]
Stu ff to parse Sun and NeXT audio files.
Inter pr et sun au dio header s.
Non-term inal sy m bols of Py thon gr am m ar (fr om "gram init.h").
Inter face to the com piler 's internal sy m bol tables.
Sy stem -specific param eters and fu nctions.
Pr ov ides access to Py thons configur ation inform ation like the list of installation paths and the
configuration v ariables relev ant for the curr ent platform .
Unix sy slog library routines [Unix].
Check Py thon sou rce for am biguous indentation.
Tools to read and create TAR archiv es. 2 .5: New m ethod TarFile.extractall() .
TELNET client class. Based on RFC 854 .
Tem porary files and filenam es. 2 .6: New classes SpooledTemporaryFile and
NamedTemporaryFile .
POSIX sty le tty contr ol [Unix].
Regression tests package for Py thon.
Tools to wr ap paragraphs of text.
Multiple thr eads of control (see also threading below ).
New threading m odule, em u lating a subset of Jav a's threading m odel. 2 .5: New function
stack_size([size]) allows to get/set the stack size for thr eads cr eated. 2 .6: Sev eral fu nctions
renam ed or replaced by pr operties, new proper ty Thread.ident . See also new m odule
multiprocessing .
(doc of the threading m odule).
Tim e access and conv ersions.
Benchm ark tool.
Extension widgets for Tk.
Py thon interface to Tcl/Tk.
Conv er t "arbitrar y " sound files to AIFF (Apple and SGI's audio form at). Deprecated since 2 .6 .
Token constants (fr om "token.h").
Tokenizer for Py thon sou rce.
Tools to trace execution of a fu nction or program .
Extract, form at and print inform ation about Py thon stack tr aces.
Ter m inal u tilities [Unix].
LogoMation-like tu rtle graphics.
Define nam es for all ty pe sy m bols in the std interpreter .
Par se a tim ezone specification.
Inter face to u nicode proper ties. 2 .5: Updated to Unicode DB 4 .1 .0; Ver sion 3 .2 .0 still av ailable as
unicodedata.ucd_3_2_0 . 2 .6: Updated to Unicode DB 5.1 .0.
Py thon u nit testing fr am ew or k, based on Erich Gam m a's and Kent Beck's JUnit.
Open an ar bitrary URL.
An extensible libr ar y for opening URLs using a v ariety of protocols.
Par se (absolute and relativ e) URLs.
Hook to allow user-specified cu stom ization code to ru n.
A w rapper to allow subclassing of built-in dict class (useless with new-style classes. Since Py thon
2 .2 , dict is subclassable).
A w rapper to allow subclassing of built-in list class (useless with new-style classes. Since Py thon 2 .2 ,
list is subclassable)
A w rapper to allow subclassing of built-in str ing class (useless with new-style classes. Since Py thon
A w rapper to allow subclassing of built-in str ing class (useless with new-style classes. Since Py thon
2 .2 , str is subclassable).
som e u seful fu nctions that don't fit elsewhere !!
Im plem entation of the UUencode and UUdecode fu nctions.
UUID objects according to RFC 4 1 2 2 .
Py thon part of the warnings su bsy stem . Issue war nings, and filter u nw anted w arnings.
Stu ff to parse WAVE files.
Weak reference support for Py thon. Also allows the creation of pr oxy objects. 2 .5: new m ethods
UserString
util
uu
uu id
warnings
wav e
weakr ef
webbr owser
whatsou nd
whichdb
whrandom
winsound
wsgiref
xdr lib
xm l.dom
xm l.etree.Elem entTree
xm l.par sers.expat
xm l.sax
xm lr pclib
xreadlines
zipfile
zipim por t
zlib
zm od
Platform independent URL lau ncher. 2 .5: sev eral enhancem ents (m ore browsers supported, etc...).
Sev er al r outines that help recognizing sound files.
Guess w hich db package to u se to open a db file.
Wichm ann-Hill random nu m ber gener ator (obsolete, use random instead).
Sound-play ing interface for Windows [Windows].
WSGI Utilities and Reference Im plem entation.
Im plem ents (a subset of) Su n XDR (eXternal Data Representation).
Classes for pr ocessing XML using the DOM (Docum ent Object Model). 2 .3 : New m odu les
expatbuilder, m inicom pat, NodeFilter, xm lbuilder.
Su bset of Fredrik Lu ndh's Elem entTree library for processing XML.
An interface to the Expat non-v alidating XML par ser.
Classes for pr ocessing XML using the SAX API.
An XML-RPC client inter face for Py thon. 2 .5: Su pports retu rning datetime objects for the XML-RPC
date ty pe.
Pr ov ides a sequence-like object for r eading a file line-by -line without reading the entire file into
m em or y . Deprecated since release 2 .3 . Use for line in file instead. Rem ov ed since 2 .4
Read & w rite PK zipped files. 2 .5: Supports ZIP6 4 v er sion, a .zip archiv e can now be lar ger than
4GB. 2 .6: Class ZipFile has new m ethods extract() and extractall() .
ZIP archiv e im por ter.
Com pression com patible w ith gzip. 2 .5: Compress and Decompress objects now suppor t a copy()
m ethod.
Dem onstration of abstr use m athem atical concepts.
list v alid attributes of object (which can be a m odu le, ty pe or class object)
list nam es in cur rent local sy m bol table.
inv oke m ain() if running as script
m er ge lists; see also zip(lst1 , lst2 , ...)
create a copy b of sequ ence a
If a is a list, create a copy of it.
Multiple assignm ent, sam e as a= 1 ; b= 2 ; c= 3
Wor ks also in this context
Wor ks as expected
Pr ocess each file in com m and line args, one line at a tim e
(u nder score) in interactiv e m ode, refer s to the last v alu e pr inted.
P y th on M od e for Ema cs
Emacs goodies av ailable here.
(The following has not been revised, probably not up to date - any contribution welcome -)
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
Ch a n ges to th is d ocumen t
April, 2013 (Stefan McKinnon H j-Edw ards )
Cor r ect ion s
A dded st r ik eth r ou g h to depr eca t ed m odu les in m odu le-list.
Cor r ect ed lin k s in m odu les list .
A dded a r ecipee for th e secr et re.Scanner.
A dded c on t ex t m a n a g er m et h ods t o specia l m eth ods in c la sses.
Oc t, 2011 (Stefan McKinno n H j-Edw ards )
Upg r a ded to Py t h on 2 .7
Prio r to Oct. 2011,
see La st u pda t ed on -list