Você está na página 1de 41

Pyth on 2.

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.

Last updated on A pril 1 6, 201 3.


Apr 16, 2013
Som e c or r ect ion s, see bot t om , by St efa n Mc Kin n on Hj-Edw a r ds.
Oct, 2011
u pg r a ded by St efa n Mc Kin n on Hj-Edw a r ds for Py t h on 2 .7
Feb 10, 2009
u pg r a ded by Ric h a r d Gr u et a n d Josh Ston e for Py t h on 2 .6
Dec 14, 2006
u pg r a ded by Ric h a r d Gr u et for Py t h on 2 . 5
Feb 17, 2005,
u pg r a ded by Ric h a r d Gr u et for Py t h on 2 . 4
Oct 3, 2003
u pg r a ded by Ric h a r d Gr u et for Py t h on 2 . 3
May 11, 2003, rev 4
u pg r a ded by Ric h a r d Gr u et for Py t h on 2 . 2 (r est y led by A n dr ei)
Aug 7, 2001
u pg r a ded by Sim on Br u n n in g for Py t h on 2 .1
May 16, 2001
u pg r a ded by Ric h a r d Gr u et a n d Sim on Br u n n in g for Py t h on 2 .0
Jun 18, 2000
u pg r a ded by Ric h a r d Gr u et for Py t h on 1 .5 . 2
Oct 20, 1995
c r ea t ed by Ch r is Hoffm a n n for Py t h on 1 .3

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

Originally based on:


Py thon Bestiary , author: Ken Manheimer
Py thon manuals, authors: Guido v an Rossum and Fred Drake
py thon-mode.el, author: Tim Peters
and the readers of comp.lang.py thon
Useful links :

Pyt hon's nest: http://ww w.py thon.org


Official documentat ion: http://docs.py thon.or g/2 .7 /
Other doc & free books : FAQs, Div e into Py thon (from 2 004), Py thon Cookbook - Popular Py thon recipes, Thinking in
Py thon (fr om 2 001 ), Text pr ocessing in Py thon (from 2 003 )
Gett ing started: Py thon Tutor ial, 7 m n to Hello Wor ld (w indow s)
Topics: HOWTOs, Databases, Web progr am m ing, XML, Web Serv ices, Parsers, Nu m Py & SciPy - Nu m eric & Scientific
Com puting, GUI program m ing, Distr ibuting
Where t o find packages: Py thon Package Index (Py PI), Py thon Eggs, SourceForge (search "py thon"), Easy Install, O'Reilly
Py thon Dev Center
Wiki: m oinm oin
Newsgroups: com p.lang.py thon and com p.lang.py thon.announce
Misc pages: Daily Py thon URL
Pyt hon Dev elopment: http://w ww .py thon.or g/dev /
Jython - Jav a im plem entation of Py thon: http://ww w.jy thon.or g/
IronPy thon - Py thon on .Net: http://w ww .codeplex.com /Wiki/View .aspx?Pr ojectNam e=IronPy thon
Act ivePy thon: http://ww w.Activ eState.com /ASPN/Py thon/
Help desk: help@py thon.org
2 excellent (bu t som ehow ou tdated) Python reference books: Py thon Essential Reference (Py thon 2 .1 ) by Dav id Beazley &
Guido Van Rossum (Other New Rider s) and Py thon in a nu tshell by Alex m artelli (O'Reilly ).
Pyt hon 2.4 Reference Card (cheat sheet) by Laur ent Pointal, designed for pr inting (1 5 pages).
Online Py thon 2 .2 Quick Reference by the New Mexico Tech Com pu ter Center.
Tip: From w ithin the Py thon interpreter , ty pe help , help(object) or help("name") to get help.

In v oca tion Op tion s


py thon[w] [-BdEhim OQsStuUv VWxX3 ] [-c command | scriptFile | - ] [args]

(py thonw does not open a terminal/console; py thon does)


Invocation Options
Opt i on

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.

En v iron men t v a ria b les


Environment variables
V a r i a bl e

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

N ota b le lexica l en tities


Keywords
and
assert
break
class
continue
def

del
elif
else
except
exec
finally

for
from
global
if
import
in

is
lambda
not
or
pass
print

raise
return
try
while
with
yield

(List of key words av ailable in std module: key word)


Illegitimate Tokens (only v alid in strings): $ ? (plus @ before 2.4)
A statement must all be on a single line. To break a statement ov er multiple lines, use "\", as with the C preprocessor.
Ex ception: can alway s break when inside any (), [], or {} pair, or in triple-quoted strings.
More than one statement can appear on a line if they are separated with semicolons (";").
Comments start with "#" and continue to end of line.

I dent ifiers
(letter | "_") (letter | digit | "_")*

Py thon identifiers key words, attributes, etc. are case-sensitiv e.


Special forms: _ident (not imported by 'from module import *'); __ident__ (sy stem defined name); __ident (classpriv ate name mangling).

String lit erals


Two flav ors: str (standard 8 bits locale-dependent strings, like ascii, iso 8859-1 , utf-8, ...) and unicode (1 6 or 32 bits/char in utf16 mode or 32 bits/char in utf-32 mode); one common ancestor basestring .

16 mode or 32 bits/char in utf-32 mode); one common ancestor basestring .


Li t er a l

"a string enclosed by dou ble quotes"


'another string delim ited by single quotes and with a " inside'
'''a string containing em bedded new lines and quote (') m arks, can be delim ited w ith triple quotes.'''
""" m ay also u se 3 - double quotes as delim iters """
b"An 8-bit string" - A bytes instance, a forward-com patible form for an 8-bit string'
B"Another 8-bit str ing"
u'a unicode string'
U"Another unicode str ing"
r'a raw str ing where \ are kept (literalized): handy for regular expr essions and w indows paths!'
R"another r aw string" -- r aw strings cannot end with a \
ur'a unicode raw string'
UR"another raw u nicode"

Use \ at end of line to continue a string on nex t line.


A djacent strings are concatened, e.g. 'Monty ' 'Python' is the same as 'Monty Python' .
u'hello' + ' world' --> u'hello world' (coerced to unicode)
String Literal Escapes
Esca pe

Mea n i n g

\newline
\\
\e

Ignored (escape new line)


Backslash (\)
Escape (ESC)

\v
\'
\f
\ooo
\"
\n
\a
\r
\xhh
\b
\t
\uxxxx
\Uxxxxxxxx
\N{name}

Vertical Tab (VT)


Single quote (')
For m feed (FF)
char with octal v alue ooo
Double quote (")
Linefeed (LF)
Bell (BEL)
Carriage Retu rn (CR)
char with hex v alue hh
Backspace (BS)
Horizontal Tab (TAB)
Character w ith 1 6-bit hex v alu e xxxx (unicode only )
Character w ith 3 2 -bit hex v alue xxxxxxxx (unicode only )
Character nam ed in the Unicode database (u nicode only ), e.g. u'\N{Greek Small Letter Pi}' < = >
u'\u03c0'.

\AnyOtherChar

(Conv ersely , in m odu le unicodedata, unicodedata.name(u'\u03c0') == 'GREEK SMALL LETTER PI' )


left as-is, including the backslash, e.g. str('\z') == '\\z'

NUL by te (\000 ) is not an end-of-string marker; NULs may be embedded in strings.


Strings (and tuples) are immutable: they cannot be modified.

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}

Key s must be of a hashable ty pe; Values can be any ty pe.


Dictionaries are unordered, ie. iterating ov er a dictionary prov ides key /v alue pairs in arbitrary order. OrderedDict in the
collections module works as regular dictionaries but iterates ov er key s and v alues in a guaranteed order depending on when a
key was first inserted.

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.

Operat ors and t heir evaluation order


Operators and their evaluation order
Hi gh est Oper a t or

Com m en t

, [...] {...} `...`


s[i] s[i:j] s.attr f(...)
+x, -x, ~x
x**y
x*y x/y x%y
x+y x-y
x< < y x> > y
x&y
x^y
x|y
x<y x<=y x>y x>=y x==y x!=y x<>y
x is y x is not y
x in s x not in s
not x
x and y
x or y
lambda args: expr

Lowest

Tu ple, list & dict. cr eation; string conv .


indexing & slicing; attr ibutes, function calls
Unary operators
Pow er
m ult, div ision, m odulo
addition, substraction
Bit shifting
Bitw ise "and"; also inter section of sets
Bitw ise exclu siv e or
Bitw ise "or"; also u nion of sets
Com parison,
identity ,
m em bership
boolean negation
boolean and
boolean or
anony m ou s fu nction

A lternate names are defined in module operator (e.g. __add__ and add for +)
Most operators are ov erridable

Ba s ic ty p es a n d th eir op era tion s


Comparisons ( defined between any types)
Comparisons
Com pa r ison Mea n i n g

<
<=
>
>=
==
!= or <>
is
is not

strictly less than


less than or equ al to
strictly gr eater than
gr eater than or equal to
equal to
not equal to
object identity
negated object identity

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

True if expr is true, False other wise.


consider ed False
consider ed True
True if x is False, else False
if x is False then y, else x
if x is False then x, else y

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

see Tru e, False

(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

the absolu te v alue of x


x conv erted to integer
x conv erted to long integer
x conv erted to floating point
x negated
x u nchanged
the su m of x and y
difference of x and y
product of x and y
tru e div ision of x by y : 1 /2 -> 0.5
floor div ision operator: 1 //2 -> 0
x m odulo y
the tu ple (x//y, x%y)
x to the pow er y (the sam e as pow(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

the bits of x inv er ted


bitwise exclusiv e or of x and y
bitwise and of x and y
bitwise or of x and y
x shifted left by n bits

x >> n

x shifted right by n bits

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

Operat ions on all sequence t ypes ( lists, tuples, strings)


Operations on all sequence types
Oper a t i on

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 )

the concatenation of s1 and s2


n copies of s concatenated
i'th item of s, or igin 0
Slice of s from i (included) to j(exclu ded). Optional step v alu e, possibly negativ e (defau lt: 1 ).

(1 )
(1 ), (2 )

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 sequence.

(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).

Operat ions on mutable sequences ( t ype

list)

Operations on mutable sequences


Oper a t i on

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 )

s.sort ([cm p= cmpFunc]


[, key = keyGetter]
[, rev erse= bool])

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 .

Operat ions on ma ppings / dictionaries ( type

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()

The num ber of item s in d


Creates an em pty dictionary .
Creates a dictionary init w ith the key w or d args kwargs.
Creates a dictionary init w ith (key , v alu e) pair s prov ided by iterable.
Creates a dictionary w hich is a copy of dictionary d.
Class m ethod to create a dictionary w ith key s prov ided by iterator, and
all v alues set to value.
The item of d w ith key k
Set d[k] to x
Rem ov es d[k] from d
Rem ov es all item s fr om d
A shallow copy of d
True if d has key k, else False
A copy of d's list of (key , item ) pairs
A copy of d's list of key s

(1 )
(1 )

(2 )
(2 )

for k, v in d2.items(): d1[k] = v

Since 2 .4, update(**kwargs) and updat e(iterable) m ay also be used.


A copy of d's list of v alues
The item of d w ith key k
d[k] if k in d, else defaultval (and inserts it)
Retur ns an iter ator ov er (key , v alue) pairs.
Retur ns an iter ator ov er the m apping's keys.
Retur ns an iter ator ov er the m apping's values.
Rem ov es key k and r eturns the corresponding v alu e. If key is not fou nd,
default is retur ned if giv en, other wise KeyError is raised.
Rem ov es and retur ns an ar bitr ar y (key , v alu e) pair fr om d
Retur ns a view object of the (key , v alu e) pairs
Retur ns a view object of the m appings keys
Retur ns a view object of the m appings values

(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.

(2) Key s and v alues are listed in random order.


(3) Nev er raises an ex ception if k is not in the map, instead it returns defaultval. defaultval is optional, when not
prov ided and k is not in the map, None is returned.
(4) Nev er raises an ex ception if k is not in the map, instead returns defaultV al, and adds k to map with v alue defaultV al.
defaultVal is optional. When not prov ided and k is not in the map, None is returned and added to map.
(5) A view object prov ides a dy namic v iew on the dictionary 's entries, which means that when the dictionary changes,
the v iew reflects these changes. A v iew object is also iterable.

Operat ions on strings ( types

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]])

s.endswith(suffix [, start[, end]])


s.expandtabs([tabsize])
s.find(sub [,start[,end]])
s.format(*args, *kwargs)
s.index(sub[, start[, end]])
s.isalnum()
s.isalpha()
s.isdigit()
s.islower()
s.isspace()
s.ist it le()
s.isupper()
separator.join(seq)

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)

separator, e.g.: ",".join(['A', 'B', 'C']) -> "A,B,C"


Retur ns s left/right ju stified/centered in a str ing of length width.

s.ljust /rjust /center(width[,


fillChar= ' '])
s.lower()
s.lst rip([chars] )
s.partition(separ)

s.replace(old, new[, maxCount = -1 ])


s.rfind(sub[ , start[, end]])
s.rindex(sub[ , start[, end]])
s.rpartition(separ)

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)

Retur ns a copy of s conv erted to lowercase.


Retur ns a copy of s w ith leading chars (default: blank chars) r em ov ed.
Sear ches for the separ ator separ in s, and retu rns a tuple (head, sep, tail)
containing the par t before it, the separ ator itself, and the par t after it. If the
separator is not fou nd, retu rns (s, '', '').
Retur ns a copy of s w ith the fir st maxCount (-1 : u nlim ited) occu rrences of
su bstring old replaced by new.
Retur ns the highest index in s where substring sub is found. Returns -1 if sub is
not found.
like rfind(), bu t raises ValueError when the substring is not fou nd.
Sear ches for the separ ator separ in s, starting at the end of s, and r eturns a tu ple
(head, sep, tail) containing the (left) part before it, the separator itself, and
the (r ight) part after it. If the separator is not fou nd, retur ns ('', '', s).
Retur ns a copy of s w ith trailing chars(default: blank char s) rem ov ed, e.g.
aPath.rstrip('/') w ill rem ov e the trailing '/'from aPath if it exists
Retur ns a list of the w or ds in s, u sing separator as the delim iter string.
Sam e as split , but splits from the end of the string.
Retur ns a list of the lines in s, breaking at line boundaries.
Retur ns True if s starts w ith the specified prefix, otherwise r eturns False .
Negativ e num bers m ay be used for start and end. Since 2 .5 prefix can also be a
t uple of strings to tr y .
Retur ns a copy of s w ith leading and tr ailing chars(default: blank char s)
r em ov ed.
Retur ns a copy of s w ith uppercase character s conv erted to lower case and v ice
v ersa.
Retur ns a titlecased copy of s, i.e. words star t w ith uppercase characters, all
r em aining cased char acters ar e lowercase.
Retur ns a copy of s m apped thr ough translation table table. Char acters from
deletechars ar e rem ov ed from the copy prior to the m apping. Since 2 .6 table m ay
also be None (identity transform ation) - u seful for u sing translate to delet e
chars only .
Retur ns a copy of s conv erted to u ppercase.
Retur ns the num eric string left filled with zer os in a string of length 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

formatString mix es normal tex t with C printf format fields :


%[flag][w idth][.precision] formatCode

where formatCode is one of c, s, i, d, u, o, x , X, e, E, f, g, G, r, % (see table below).


The flag characters -, +, blank, # and 0 are understood (see table below).
Width and precision may be a * to specify that an integer argument giv es the actual width or precision. Ex amples of
w idth and precision :
Examples
For m a t st r i n g
'%3d' % 2
'%*d' % (3, 2)
'%-3d' % 2
'%03d' % 2
'% d' % 2
'%+d' % 2
'%+3d' % -2
'%- 5d' % 2
'%.4f' % 2

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'

%s will conv ert any ty pe argument to string (uses str() function)


args may be a single arg or a tuple of args
'%s has %03d quote types.' % ('Python', 2)

== 'Python has 002 quote types.'

Right-hand-side can also be a mapping:

a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python'}

(vars() function v ery handy to use on right-hand-side)


Format codes
Code

d
i
o
u
x
X
e
E
f
F
g
G
c
r
s
%

Mea n i n g

Signed integer decim al.


Signed integer decim al.
Unsigned octal.
Unsigned decim al.
Unsigned hexadecim al (lower case).
Unsigned hexadecim al (upper case).
Floating point exponential for m at (lower case).
Floating point exponential for m at (u ppercase).
Floating point decim al for m at.
Floating point decim al for m at.
Sam e as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
Sam e as "E" if exponent is greater than -4 or less than precision, "F" other wise.
Single character (accepts integer or single char acter string).
Str ing (conv erts any py thon object using repr() ).
Str ing (conv erts any py thon object using str() ).
No argu m ent is conv er ted, r esults in a "%" char acter in the resu lt. (The com plete specification is %%.)

Conversion flag characters


Fl a g Mea n i n g

#
0
+

The v alue conv ersion will u se the "alternate for m ".


The conv er sion will be zer o padded.
The conv er ted v alue is left adju sted (ov errides "-").
(a space) A blank shou ld be left before a positiv e nu m ber (or em pty str ing) pr oduced by a signed conv ersion.
A sign character ("+ " or "-") w ill precede the conv er sion (ov errides a "space" flag).

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

Sign flag characters


Fl a g Mea n i n g

+
-

Display s a sign for all nu m bers


Display s a sign for negativ e nu m ber s only (default)
(a space) Display s a sign for negativ e num bers and a space for positiv e num bers

Integer type flags


Fl a g Mea n i n g

b
c
d
o
x
X

Binary form at (base 2 )


Character (inter pr ets integer as a Unicode code point)
Decim al for m at (base 1 0) (defau lt)
Octal form at (base 8)
Hexadecim al form at (base 1 6) (lowercase)
Hexadecim al form at (base 1 6) (u ppercase)

Floating-point type flags


Fl a g Mea n i n g

e
E
f
F
g
G
n
%

Exponential for m at (lowercase)


Exponential for m at (u ppercase)
Fixed-point form at
Fixed-point form at (sam e as "f")
General for m at - sam e as "e" if exponent is greater than -4 or less than pr ecision, "f" otherw ise. (default)
General for m at - Sam e as "E" if exponent is gr eater than -4 or less than precision, "F" otherw ise.
Nu m ber form at - Sam e as "g", except it uses locale settings for separators.
Percentage - Multiplies by 1 00 and display s as "f", follow ed by a percent sign.

For ex amples, see Format ex amples in the Py thon documentation.

Operat ions on files ( type

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

Ot h er I/O-r ela t ed I/O oper a tion fa ilu r e

Operat ion on sets ( types

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

instead of square brackets.


Classes Sets and ImmutableSet in the module sets is now deprecated.
Main Set operations
Oper a t i on

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

Ellipsis object, u sed by extended slice notation (unique, nam ed Ellipsis)


Null object (u niqu e, nam ed None )
XRange objects
Callable ty pes:
User-defined (written in Py thon):
User-defined Function objects
User-defined Method objects
Built-in (wr itten in C):
Built-in Function objects
Built-in Method object
Int ernal Ty pes:
Code objects (by te-com pile executable Py thon code: bytecode)
Frame objects (execution fr am es)
Traceback objects (stack trace of an exception)

S ta temen ts
St a t em en t

Resu lt

pass
del name[, name]*
print[>> fileobject,] [s1 [, s2 ]* [,]

exec x [in globals [, locals]]

callable(value,... [id= value] , [*args],


[**kw])

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

Basic assignm ent - assign object b to label a


Roughly equiv alent to a = a + b
Roughly equiv alent to a = a - b
Roughly equiv alent to a = a * b
Roughly equiv alent to a = a / b
Roughly equiv alent to a = a // b
Roughly equiv alent to a = a % b
Roughly equiv alent to a = a ** b
Roughly equiv alent to a = a & b
Roughly equiv alent to a = a | b
Roughly equiv alent to a = a ^ b
Roughly equiv alent to a = a > > b
Roughly equiv alent to a = a < < b

(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'

Tip: x,y = y,x swaps x and y.


(2) Multiple assignment possible:
a = b = c = 0
list1 = list2 = [1, 2, 3]

# list1 and list2 points to the same list (l1 is l2)

(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.

Condit ional Expressions

Conditional Expressions (not statements) hav e been added since 2.5 [PEP 308]:
result = (whenTrue if condition else whenFalse)

is equiv alent to:


if condition:
result = whenTrue
else:
result = whenFalse

() are not mandatory but recommended.

Control Flow st atement s


Control flow statements
St a t em en t

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

assert expr[, message]


try:
block1
[except [exception [, value]]:
handler]+
[except [exception [as value]]:
handler]+
[else:
else-block]
try:
block1
finally:
final-block
try:
block1
[except [exception [, value]]:
handler1]+
[except [exception [as value]]:
handler]+
[else:
else-block]
finally:
final-block
with allocate-expression [as variable]:
with-block
with allocate-expression as variable [,
allocate-expression2 as variable2:
with-block

Resu l t

expr is ev aluated. if false, raises exception AssertionError with m essage. Before 2 .3 ,


inhibited if __debug__ is 0.
Statem ents in block1 are executed. If an exception occurs, look in except clau se(s) for
m atching exception(s). If m atches or bar e except, execute handler of that clause. If no
exception happens, else-block in else clause is execu ted after block1. If exception has a
v alue, it is put in v ariable value. exception can also be a tuple of exceptions, e.g.
except(KeyError, NameError), e: print e.
2 .6 also supports the key w ord as instead of a com m a betw een the exception and the
value, which w ill becom e a m andator y change in Py thon 3 .0 [PEP3 1 1 0].
Statem ents in block1 are executed. If no exception, execu te final-block (ev en if block1 is
exited with a return , break or continue statem ent). If exception did occur , execu te
final-block and then im m ediately re-raise exception. Ty pically u sed to ensu re that a
resou rce (file, lock...) allocated before the try is fr eed (in the final-block ) w hatev er
the outcom e of block1 execution. See also the with statem ent below.
Unified try /except/finally . Equ iv alent to a try...except nested inside a
try..finally [PEP3 41 ]. See also the w ith statem ent below .

Alternativ e to the try...finally str uctu re [PEP3 43 ].


allocate-expression should ev aluate to an object that supports the context management
protocol, representing a r esour ce. This object m ay r eturn a v alu e that can optionally
be bound to variable (v ariable is not assigned the resu lt of expr ession).
The object can then r un set-up code before with-block is executed and som e cleanup code is execu ted after the block is done, ev en if the block raised an exception.
Standard Py thon objects su ch as files and locks suppor t the context m anagem ent
protocol:
with open('/etc/passw d', 'r') as f: # file au tom atically closed on block exit
for line in f:
print line

print line
with threading.Lock(): # lock au tom atically released on block exit
do som ething...

raise exceptionI nstance


raise exceptionClass [, value [,
traceback]]
raise

- You can w rite y our ow n context m anagers.


- Helper functions are av ailable in m odu le contextlib.
In 2 .5 the statem ent m ust be enabled by : from __future__ import
with_statement. The statem ent is alway s enabled star ting in Py thon 2 .6.
Raises an instance of a class deriv ed from BaseException (preferred form of r aise).
Raises exception of giv en class exceptionClass with optional v alue value. Arg traceback
specifies a tr aceback object to u se when printing the exception's backtrace.
A r aise statem ent w ithou t argu m ents re-raises the last exception raised in the cur rent
function.

A n ex ception is an instance of an exception class.


Ex ception classes must be deriv ed from the predefined class: Ex ception, e.g.:
class TextException(Exception): pass
try :
if bad:
raise TextException()
except Exception:
print 'Oops' # This will be printed because TextException is a subclass of Exception

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).

Name Space St atements


Imported module files must be located in a directory listed in the Py thon path (sys.path ). Since 2.3, they may reside in a zip
file [e.g. sy s.path.insert(0, "aZipFile.zip")].
Absolute/relativ e im ports (since 2.5 [PEP328]):
Feature must be enabled by : from __future__ import absolute_import : will probably be adopted in 2.7 .
Imports are normally relative: modules are searched first in the current directory /package, and then in the builtin
modules, resulting in possible ambiguities (e.g. masking a builtin sy mbol).
When the new feature is enabled:
import X will look up for module X in sys.path first (absolute import).
import .X (with a dot) will still search for X in the current package first, then in builtins (relative import).
import ..X will search for X in the package containing the current one, etc...
Packages (>1 .5): a package is a name space which maps to a directory including module(s) and the special initialization
module __init__.py (possibly empty ).
Packages/directories can be nested. Y ou address a module's sy mbol v ia [package.[package...].module.symbol .
[1 .51 : On Mac & Windows, the case of module file names must now match the case as used in the import statement]

Name space statements


St a t em en t

import module1 [as name1] [,


module2]*

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()

from module import name1 [as


othername1][, name2]*

module1 renam ed as name1, if su pplied.


Im por ts nam es fr om m odule module in cu rrent nam espace.
from sys import argv; print argv
from package1 import module; module.foo()
from package1.module import foo; foo()

from module import *

name1 r enam ed as othername1, if supplied.


[2 .4] You can now put parentheses around the list of nam es in a from module import
names statem ent (PEP 3 2 8).
Im por ts all nam es in module, except those starting with "_". Use sparsely, beware of
name clashes!
from sys import *; print argv
from package.module import *; print x

Only legal at the top lev el of a m odu le.


If module defines an __all__ attribu te, only nam es listed in __all__ w ill be im ported.
NB: "from package import * " only im ports the sy m bols defined in the package's
__init__.py file, not those in the package's m odu les !

global name1 [, name2]

Nam es are fr om global scope (usually m eaning from m odu le) rather than local (u sually

m eaning only in function).


E.g. in function w ithout global statem ents, assu m ing "x" is nam e that hasn't been u sed in
function or m odule so far:
- Try to read from "x" -> NameError
- Try to write to "x" -> creates "x" local to function
If "x" not defined in fu nction, but is in m odu le, then: - Try to read from "x", gets v alu e from
m odu le
- Try to write to "x", cr eates "x" local to fu nction
But note "x[0]= 3 " star ts with search for "x", w ill use to global "x" if no local "x".

Function Definition
def funcName ([paramList]) :
suite

Creates a function object and binds it to nam e funcName.


paramList ::= [param [, param]*]
param ::= value | id=value | * id | ** id

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)

Since 2.6, **kwargs can be any mapping, not only a dict .


See also Anony mous functions (lambdas).

Class Definit ion


class className [(super_class1[, super_class2]*)]:
suite

Creates a class object and assigns it nam e className.


suite m ay contain local "defs" of class m ethods and assignm ents to class attribu tes.

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']

New-style classes ex tends object . Old-style classes don't.


Do c u m e n t a t io n St rin g s
Modules, classes and functions may be documented by placing a string literal by itself as the first statement in the suite. The
documentation can be retriev ed by getting the '__doc__' attribute from the module, class or function.
Ex ample:
class C:
"A description of C"
def __init__(self):
"A description of the constructor"
# etc.
c.__doc__ == "A description of C".
c.__init__.__doc__ == "A description of the constructor"

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:

when assigning tuples: x,y,z= 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...

Generator ex pressions must appear between parentheses.


[PEP342] Generators before 2.5 could only produce output. Now v alues can be passed to generators v ia their method
send(value) . yield is now an expression returning a v alue, so val = (yield i) will yield i to the caller, and will
reciprocally ev aluate to the v alue "sent" back by the caller, or None .
Two other new generator methods allow for additional control:
throw(type, value=None, traceback=None) is used to raise an ex ception inside the generator (appears as raised
by the yield ex pression).
close() raises a new GeneratorExit ex ception inside the generator to terminate the iteration.
Since 2.6 Generator objects hav e a gi_code attribute that refers to the original code object backing the generator.
Ex ample:
def genID(initialValue=0):
v = initialValue
while v < initialValue + 1000:
yield "ID_%05d" % v
v += 1
return
# or: raise StopIteration()
generator = genID() # Create a generator
for i in range(10): # Generates 10 values
print generator.next()

Descriptors / Att ribute access


Descriptors are objects implementing at least the first of these 3 methods representing the descriptor protocol:
__get__(self, obj, type=None) --> value
__set__(self, obj, value)
__delete__(self, obj)

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.

Decorators for functions, met hods & classes


[PEP 31 8] A decorator D is noted @D on the line preceding the function/method it decorates :
@D
def f(): ...

and is equiv alent to:


def f(): ...
f = D(f)

thus, a decorator can be any function returning another function usually applied as a function transformation.
Sev eral decorators can be applied in cascade :

Sev eral decorators can be applied in cascade :


@A
@B
@C
def f(): ...

is equiv alent to:


f = A(B(C(f)))

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) .

[PEP 31 29] Decorators may also be applied to classes:


@D
class C(): ...

is equiv alent to:


class C(): ...
C = D( C )

Som e selected decorators


@staticmethod - makes a method static (unbound) from an instance.
@classmethod - A class method receiv es the class as implicit first argument, just like an instance method receiv es the
instance.
@prop.getter , @prop.setter and @prop.deleter - Use a function for getting, setting or deleting the property prop

Misc
lambda [param_list]: returnedExpr

Creates an anonymous fu nction.


returnedExpr m ust be an expression, not a statem ent (e.g., not "if xx:...", "pr int xxx", etc.) and thus can't contain new lines. Used
m ostly for filter (), m ap(), reduce() fu nctions, and GUI callbacks.

List comprehensions
result = [ expression for item1 in sequence1 [if condition1]
[for item2 in sequence2 ... for itemN in sequenceN]
]

is equ iv alent to:


result = []
for item1 in sequence1:
for item2 in sequence2:
...
for itemN in sequenceN:
if (condition1) and further conditions:
result.append(expression)

List comprehensions for dict ionaries and set s


>>> {x: x*x for x in range(6)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Dictionary

Equiv alent to:


>>> dict([(x, x*x) for x in range(6)])

Sets:
>>> {('a'*x) for x in range(6)}
set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

See also Gener ator expressions.

Built-In Fun ction s


Built-in functions are defined in a module

automatically imported.

Built-in functions are defined in a module _builtin__ automatically imported.


Built-In Functions
Fu n ct i on

__import __(name[,
globals[,locals[,from list]]])
abs(x)
all(iterable)
any(iterable)
apply(f, args[, keywords])
basestring()
bin(x)
bool([x])

buffer(object[, offset[, size]])


by tearray (iterable)
by tearray (length)
by tes(object)

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]])

Returns negativ e, 0, positiv e if x < , = = , > to y respectiv ely .


Returns a tuple of the two numeric ar gum ents conv erted to a com m on ty pe. Non essential
function, see [details]
Com piles string into a code object. filename is u sed in error m essage, can be any string. It is
u sually the file from which the code was r ead, or e.g. '<string>' if not read from file. kind can
be 'eval' if string is a single stm t, or 'single' w hich prints the output of expression statem ents
that ev alu ate to som ething else than None, or be 'exec'. New args flags and dont_inherit concern
future statem ents. Since 2 .6 the function accepts keyword ar gu m ents as w ell as positional
param eters.
Creates a complex object (can also be done using J or j su ffix, e.g. 1+3J ). Since 2 .6 , also accepts
strings, w ith or without par enthesis, e.g. complex('1+3J') or complex('(1+3J)') .
Deletes the attribu te nam ed name of object obj <= > del obj.name
Returns a new dictionar y initialized fr om the optional argum ent (or an em pty dictionary if no
ar gu m ent). Ar gu m ent m ay be a sequence (or any thing iter able) of pair s (key ,v alue).
Without ar gs, retu rns the list of nam es in the curr ent local sy m bol table. With a m odu le, class or
class instance object as arg, returns the list of nam es in its attr. dictionary . Since 2 .6 object can
ov er ride the std im plem entation v ia special m ethod __dir__() .
Returns tuple (a//b, a%b)
Iterator retur ning pairs (index, item ) fr om iterable, e.g. List(enumerate('Py')) -> [(0,
'P'), (1, 'y')] . 2 .6 : Arg start specifies initial index v alue (defau lt: 0).
Ev alu ates str ing s, repr esenting a single py thon expression, in (optional) globals, locals contexts.
s m ust hav e no NUL's or newlines. s can also be a code object. locals can be any m apping ty pe,
not only a regu lar Py thon dict.
Exam ple:
x = 1; assert eval('x + 1') == 2

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.

get att r(object,name[,default]))


globals()
hasattr(object, name)
hash(object)
help([object])

hex(x)
id(object)
input([prompt])

int (x[, base])


int ern(aString)
isinstance(obj, classI nfo)

iterable, or em pty by defau lt. See also Sets.


Gets attribu te called name from object, e.g. getattr (x, 'f') < = > x.f). If not found, raises
AttributeError or retu rns default if specified.
Returns a dictionary containing the cu rrent global v ariables.
Returns tru e if object has an attribu te called name.
Returns the hash v alue of the object (if it has one).
Inv okes the built-in help sy stem . No argu m ent -> interactiv e help; if object is a string (name of
a m odule, function, class, m ethod, key w ord, or docum entation topic), a help page is printed on
the console; otherwise a help page on object is generated.
Conv erts a nu m ber x to a hexadecim al str ing.
Returns a unique integer identifier for object. Since 2 .5 alway s retur ns non-negativ e num bers.
Pr ints prompt if giv en. Reads input and evaluates it. Uses line editing / history if m odu le
readline av ailable.
For u n-ev alu ated inpu t, see raw_input .
Conv erts a nu m ber or a string to a plain integer. Optional base param eter specifies base from
w hich to conv ert str ing v alues.
Enters aString in the table of interned strings and retu rns the string. Since 2.3, interned
strings are no longer 'immort al' (never garbage collect ed), see [details]
Returns tru e if obj is an instance of class classI nfo or an object of type classI nfo (classI nfo m ay
also be a t uple of classes or ty pes). If issubclass(A,B) then isinstance(x,A) = >
isinstance(x,B)

issubclass(class1, class2)
it er(obj[,sentinel])

len(obj)
list([seq])
locals()
long(x[, base])
map(function, sequence[,
sequence, ...])

max(iterable[, key= func])


max(v1, v2, ...[, key= fu nc])

min(iterable[, key= fu nc])


min(v1, v2, ...[, key= func])

next(iterator[, default])
object ()
oct(x)
open(filename [, mode='r',
[bufsize]])

Returns tru e if class1 is deriv ed from class2 (or if class1 is class2).


Returns an iterat or on obj. If sentinel is absent, obj m ust be a collection im plem enting either
__iter__() or __getitem__() . If sentinel is giv en, obj w ill be called with no ar g; if the v alue
r eturned is equ al to sentinel, StopIteration w ill be raised, otherw ise the v alue w ill be retur ned.
See Iterators.
Returns the length (the num ber of item s) of an object (sequence, dictionar y , or instance of class
im plem enting __len__).
Creates an em pty list or a list 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 list, r eturns a shallow copy of it.
Returns a dictionary containing cu rrent local v ariables.
Conv erts a nu m ber or a string to a long integer . Optional base param eter specifies the base from
w hich to conv ert str ing v alues.
Returns a list of the r esults of apply ing function to each item from sequence(s). If m ore than one
sequ ence is giv en, the fu nction is called with an argum ent list consisting of the corresponding
item of each sequ ence, substitu ting None for m issing v alues when not all sequences hav e the
sam e length. If function is None , r eturns a list of the item s of the sequence (or a list of tuples if
m or e than one sequence). = > You m ight also consider using list comprehensions inst ead of
map().
With a single argum ent iterable, retu rns the largest item of a non-em pty iterable (su ch as a
string, tu ple or list). With m ore than one ar gu m ent, retur ns the largest of the ar gu m ents. The
optional key ar g is a fu nction that takes a single argum ent and is called for ev ery v alue in the
list.
With a single argum ent iterable, retu rns the smallest item of a non-em pty iter able (such as a
string, tu ple or list). With m ore than one ar gu m ent, retur ns the sm allest of the argum ents. The
optional key ar g is a fu nction that takes a single argum ent and is called for ev ery v alue in the
list.
Returns the next item from iterator. If iter ator exhausted, retur ns default if specified, or raises
StopIteration otherwise.
Returns a new featureless object. object is the base class for all new style classes, its m ethods ar e
com m on to all instances of new sty le classes.
Conv erts a nu m ber to an octal string.
Returns a new file object. See also alias file(). Use codecs.open() instead to open an encoded file
and prov ide transparent encoding / decoding.
filename is the file nam e to be opened
mode indicates how the file is to be opened:
'r ' for reading
'w ' for w riting (tr uncating an existing file)
'a' opens it for appending
'+ ' (appended to any of the prev ious m odes) open th e file for u pdating (note that
'w + 'truncates the file)
'b' (appended to any of the prev ious m odes) open the file in binar y m ode
'U' (or 'rU') open the file for r eading in Universal Newline mode: all v ariants of EOL
(CR, LF, CR+ LF) will be translated to a single LF ('\n').
bufsize is 0 for u nbuffered, 1 for line buffered, negativ e or om itted for sy stem defau lt, > 1
for a buffer of (about) the giv en size.

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 =

print(*args [, sep= ' ']


[, end= '\n'] [, file= sy s.stdout])

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'

can now be w ritten in this functional form :


print('foo', 42)
print('foo', 42, end='')
print('warning', file=sys.stderr)

range([start,] end [, step])

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)

Returns list of ints from > = start and < end.


With 1 ar g, list from 0..arg-1
With 2 args, list fr om start..end-1
With 3 args, list fr om start up to end by step
Pr ints prompt if giv en, then reads string from std input (no tr ailing \n). See also inpu t().
Applies the binar y function f to the item s of list so as to r educe the list to a single v alue. If init is
giv en, it is "prepended" to list.
Re-parses and r e-initializes an alr eady im ported m odu le. Useful in interactiv e m ode, if y ou w ant
to reload a m odule after fixing it. If m odule was sy ntactically correct bu t had an error in
initialization, m ust im por t it one m ore tim e befor e calling r eload().
Returns a str ing containing a printable and if possible evaluable r epresentation of an object.
< = > `object` (using backquotes). Class r edefinable ( __repr__ ). See also str()
Returns the floating point v alu e x r ounded to n digits after the decim al point.
Returns a set object w hose elem ents are taken fr om iterable, or em pty by defau lt. See also Sets.
This is the counterpart of getattr().setattr(o, 'foobar', 3 ) < => o.foobar = 3 . Creates attribute if it
doesn't exist!
Returns a slice object repr esenting a range, w ith R/O attribu tes: start, stop, step.
Returns a new sorted list fr om the item s in iterable. This contrasts with list.sort() that sorts
lists in place and doesn't apply to im m utable sequences like str ings or tu ples. See sequences.sor t
m ethod.
Returns a static m ethod for function. A static m ethod does not receiv e an im plicit first ar gu m ent.
To declare a static m ethod, use this idiom :
class C:
def f(arg1, arg2, ...): ...
f = staticmethod(f)

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])

xrange(start [, end [, step]])


zip(seq1[, seq2,...])

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).

Built-In Excep tion cla s s es


BaseEx ception
Mother of all ex ceptions (was Exception before 2.5). New-sty le class. exception.args is a tuple of the arguments passed to the
constructor.Since 2.6 the exception.message attribute is deprecated.
KeyboardInterrupt & SystemExit were mov ed out of Exception because they don't really represent errors, so now a

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

catch ev ery thing.


GeneratorExit
Raised by the close() method of generators to terminate the iteration. Before 2.6 was deriv ed from Exception .
Key boardInterrupt
On user entry of the interrupt key (often `CTRL-C'). Before 2.5 was deriv ed from Exception .
Sy stem Ex it
On sys.exit() . Before 2.5 was deriv ed from Exception .
Ex ception
Base of all errors. Before 2.5 was the base of all ex ceptions.
GeneratorExit
Mov ed under BaseException .
StandardError
Base class for all built-in ex ceptions; deriv ed from Exception root class.
Arithm eticError
Base class for arithmetic errors.
FloatingPointError
When a floating point operation fails.
Ov erflowError
On ex cessiv ely large arithmetic operation.
ZeroDiv isionError
On div ision or modulo operation with 0 as 2nd argument.
AssertionError
When an assert statement fails.
AttributeError
On attribute reference or assignment failure
Env ironm entError
On error outside Py thon; error arg. tuple is (errno, errMsg...)
IOError
I/O-related operation failure.
OSError
Used by the os module's os.error ex ception.
WindowsError
When a Windows-specific error occurs or when the error number does not correspond to an
errno v alue.
EOFError
Immediate end-of-file hit by input() or raw_input()
Im portError
On failure of import to find module or name.
Key boardInterrupt
Mov ed under BaseException.
LookupError
base class for Index Error, Key Error
Index Error
On out-of-range sequence subscript
Key Error
On reference to a non-ex istent mapping (dict) key
Mem ory Error
On recov erable memory ex haustion
Nam eError
On failure to find a local or global (unqualified) name.
UnboundLocalError
On reference to an unassigned local v ariable.
ReferenceError
On attempt to access to a garbage-collected object v ia a weak reference prox y .
Runtim eError
Obsolete catch-all; define a suitable error instead.
NotIm plem entedError
On method not implemented.
Sy ntax Error
On parser encountering a sy ntax error
IndentationError
On parser encountering an indentation sy ntax error
T abError
On improper mix ture of spaces and tabs
Sy stem Error
On non-fatal interpreter error - bug - report it !
T y peError
On passing inappropriate ty pe to built-in operator or function.
ValueError
On argument error not cov ered by TypeError or more precise.
UnicodeError

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.

S ta n d a rd meth od s & opera tors red efin ition in cla s s es


Standard methods & operators map to special methods '__method__' and thus can be redefined (mostly in user-defined
classes), e.g.:
class C:
def __init__(self, v): self.value = v
def __add__ (self, r): return self.value + r
a = C(3) # sort of like calling C.__init__(a, 3)
a + 4
# is equivalent to a.__add__(4)

Special methods for any class


Met h od

__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(),

__exit__(self, type, value,

but ignor ed u nless __getattr__ or __getattribute__ is defined.


Called w hen setting an attr ibute (inside, don't use "self.name = value", use instead
"self.__dict__[name] = value")
Called to delete attribute < name> .
Called w hen an instance is called as fu nction: obj(arg1, arg2, ...) is a shorthand for
obj.__call__(arg1, arg2, ...).
For use w ith context m anagers, i.e. when entering the block in a w ith-statem ent. The with
statem ent binds this m ethod's retu rn v alu e to the as object.
When exiting the block of a w ith-statem ent. If no err ors occured, type, value, traceback are

traceback)

None . If an er ror occur ed, they w ill contain inform ation about the class of the exception, the

__setat tr__(self, name, value)


__delattr__(self, name)
__call__(self, *args, **kwargs)
__ent er__(self)

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)

length of object, > = 0. Length 0 = = false


Get elem ent at indice /key k (indice starts at 0). Or , if k is a slice object, retu rn

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)

Delete elem ent at indice/key /slice k.


More efficient than std iteration thr u sequence.
Retu rns an iterator on elem ents (key s for m appings < = > self.iterkey s()). See
iterators.

Sequ en ces, gen er a l m et h ods, pl u s:

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)

Deprecated since 2 .0, r eplaced by __getitem__ with a slice object as


par am eter .
Deprecated since 2 .0, r eplaced by __setitem__ with a slice object as
par am eter .
Sam e as self[i:j] = [] - Deprecated since 2 .0, r eplaced by __delitem__ with a
slice object as par am eter .
(__repeat__ in the official doc but doesn't w ork!)
(__concat__ in the official doc but doesn't work!)

Ma ppi n gs, gen er a l m et h ods, pl u s:

hash(self)

__hash__(self)

hashed v alu e of object self is used for dictionary key s

S p ecia l in forma tiv e s ta te a ttr ib utes for s ome ty pes :


T ip: use module inspect to inspect liv e objects.
Lists & Dictionaries
A t t r i bu t e

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__

(str ing/None, R/O): doc str ing (< = > __dict__['__doc__'])


(str ing, R/O): m odule nam e (also in __dict__['__nam e__'])
(str ing/None, R/W): If defined, package nam e used for relativ e im ports (also in __dict__['__package__']).
[PEP3 6 6].
(dict, R/O): m odule's nam e space
(str ing/u ndefined, R/O): pathnam e of .py c, .py o or .py d (undef for m odules statically linked to the inter preter).
(list/undefined, R/W): List of directory paths w her e to find the package (for packages only ).

__dict__
__file__
__pat h__
Classes
A t t r i bu t e

Mea n i n g

__doc__
__name__
__module__
__bases__
__dict__

(string/None, R/W): doc str ing (< = > __dict__['__doc__'])


(string, R/W): class nam e (also in __dict__['__nam e__'])
(string, R/W): m odule nam e in w hich the class w as defined
(tuple, R/W): parent classes
(dict, R/W): attr ibutes (class nam e space)

Instances
A t t r i bu t e

__class__
__dict__

Mea n in g

(class, R/W): instance's class


(dict, R/W): attr ibutes

User defined functions


A t t r i bu t e

Mea n i n g

__doc__
__name__
func_doc
func_name
func_defaults
func_code
func_globals

(string/None, R/W): doc string


(string, R/O): function nam e
(R/W): sam e as __doc__
(R/O, R/W fr om 2 .4): sam e as __nam e__
(tu ple/None, R/W): default args v alues if any
(code, R/W): code object repr esenting the com piled function body
(dict, R/O): ref to dictionary of fu nc global v ariables

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

(string/None, R/O): Doc str ing


(string, R/O): Method nam e (sam e as im _fu nc.__nam e__)
(class, R/O): Class defining the m ethod (m ay be a base class)
(instance/None, R/O): Tar get instance object (None if unbound). Since 2 .6 u se __self__ instead, will be depr ecated
in 3 .0.
(instance/None, R/O): Tar get instance object (None if unbound).
(function, R/O): Fu nction object. Since 2 .6 u se __func__ instead, will be depr ecated in 3 .0.
(function, R/O): Fu nction object.

Built-in Functions & methods


A t t r i bu t e

__doc__
__name__
__self__
__members__

Mea n i n g

(string/None, R/O): doc string


(string, R/O): function nam e
[m ethods only ] tar get object
list of attr nam es: ['__doc__','__nam e__','__self__']) Deprecated, u se dir() instead.

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

(string, R/O): function nam e


(int, R/0): num ber of positional args
(int, R/O): nu m ber of local v ars (including args)
(tu ple, R/O): nam es of local v ar s (starting w ith ar gs)
(string, R/O): sequence of by tecode instructions
(tu ple, R/O): liter als used by the by tecode, 1 st one is fu nction doc (or None)
(tu ple, R/O): nam es u sed by the by tecode
(string, R/O): filenam e from w hich the code w as com piled
(int, R/O): first line num ber of the fu nction
(string, R/O): string encoding by tecode offsets to line num bers.
(int, R/O): requ ired stack size (inclu ding local v ar s)
(int, R/O): flags for the inter preter bit 2 set if fu nction uses "*arg" sy ntax, bit 3 set if function uses
'**key words' sy ntax

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

(fram e/None, R/O): prev iou s stack fr am e (toward the caller)


(code, R/O): code object being execu ted in this fr am e
(dict, R/O): local v ars
(dict, R/O): global v ars
(dict, R/O): built-in (intrinsic) nam es
(int, R/O): flag indicating whether fu nction is executed in restricted m ode
(int, R/O): curr ent line num ber
(int, R/O): precise instru ction (index into by tecode)
(function/None, R/W): debu g hook called at star t of each source line
(Ty pe/None, R/W): Most recent exception ty pe
(any , R/W): Most recent exception v alue
(traceback/None, R/W): Most recent exception 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

(any /None, R/O): lowerbou nd, included


(any /None, R/O): upperbou nd, exclu ded
(any /None, R/O): step v alu e

Complex numbers
A t t r i bu t e Mea n in g

real

(float, R/O): real part

imag

(float, R/O): im aginary part

xranges
A t t r i bu t e Mea n in g

tolist

(Built-in m ethod, R/O): ?

Imp orta n t M od ules


sys
Sy stem-specific parameters and functions.
Some sys variables
V a r i a bl e

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 ').

Some sys functions


Fu n ct i on

Resu lt

_cu rrent_fr am es()

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

nam e of O/S-specific m odule (e.g. "posix", "m ac", "nt")


O/S-specific m odule for path m anipu lations.
On Unix, os.path.split() < = > posixpath.split()
string u sed to repr esent cur rent directory (eg '.')
string u sed to repr esent par ent directory (eg '..')
string u sed to separate dir ector ies ('/' or '\'). Tip: Use os.path.join() to bu ild portable paths.
Alternate separator if applicable ( None otherw ise)
character u sed to separate sear ch path com ponents (as in $PATH), eg. ';' for windows.
line separator as u sed in t ext files, ie '\n' on Unix, '\r\n' on Dos/Win, '\r' on Mac.

Some os functions
Fu n ct i on

m akedir s(path[, mode= 07 7 7 ])


rem ov edirs(path)
renam es(old, new)
urandom (n)

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

dictionary of env ironm ent v ariables, e.g. posix.environ['HOME'] .


exception r aised on POSIX-r elated error.
Corr esponding v alue is tu ple of err no code and perror() string.

Some posix functions


Fu n ct i on

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)

Calls the sy stem call getsid() [Unix].


Like C's for k(). Retu rns 0 to child, child pid to par ent [Not on Window s].
Like C's kill [Not on Window s].
Lists (base)nam es of entr ies in directory path, excluding '.' and '..'. If path is a Unicode str ing, so will
be the retu rned strings.
Sets curr ent position in file fd to position pos, expr essed as an offset r elativ e to beginning of file
(how =0), to cu rrent position (how= 1 ), or to end of file (how= 2 ).
Cr eates a directory nam ed path w ith num eric mode (defau lt 07 7 7 ). Actu al per m issions = (mode &
~u m ask & 07 7 7 ). To set directly the per m issions, u se chmod() after dir cr eation.
Like C's open(). Retu rns file descr iptor. Use file object functions rather than this low lev el ones.
Cr eates a pipe. Retu rns pair of file descr iptors (r, w ) [Not on Windows].
Opens a pipe to or fr om command. Resu lt is a file object to read to or w rite fr om , as indicated by
mode being 'r' or 'w '. Use it to catch a com m and ou tpu t ('r' m ode), or to feed it ('w' m ode).
See unlink .
Renam es/m ov es the file or directory old to new. [error if target nam e already exists]
Recur siv e directory or file renam ing function. Works like renam e(), except creation of any
interm ediate dir ector ies needed to m ake the new pathnam e good is attem pted first. After the
renam e, directories cor responding to rightm ost path segm ents of the old nam e w ill be pruned
away u sing r em ov edirs().
Rem ov es the em pty dir ectory path
Reads n by tes from file descriptor fd and r eturn as string.
Retu rns st_m ode, st_ino, st_dev , st_nlink, st_uid,st_gid, st_size, st_atim e, st_m tim e, st_ctim e.
[st_ino, st_u id, st_gid are dum m y on Window s]
Executes string command in a su bshell. Returns exit status of subshell (usu ally 0 m eans OK). Since
2 .4 use su bprocess.call() instead.
Retu rns accu m u lated CPU tim es in sec (u ser, sy stem , children's user, children's sy s, elapsed real
tim e) [3 last not on Windows].
Unlinks ("deletes") the file (not dir!) path. Sam e as: remove .
Sets the access & m odified tim e of the file to the giv en tu ple of v alu es.
Waits for child process com pletion. Retu rns tuple of pid, exit_statu s [Not on Windows].
Waits for process pid to com plete. Retur ns tuple of pid, exit_statu s [Not on Windows].
Generates a list of file nam es in a dir ector y tr ee, by w alking the tr ee either top dow n or bottom u p.
For each directory in the tree r ooted at directory top (including top itself), it y ields a 3 -tu ple
(dirpath, dirnam es, filenam es) - m ore info her e. See also os.path.walk() .
2 .6: New followlinks param eter. If True , v isit directories pointed to by links (beware of infinite
recur sion!).
Writes str to file fd. Retur ns nb of by tes w ritten.

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

copy (src, dest)


copy tr ee(src, dest[, symlinks= False
[, ignore=None]])

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]]]]]]])

Recur siv ely m ov es a file or directory to a new location.


Deletes an entire directory tree, ignor ing err ors if ignore_errors is true, or calling
onerror(func, path, sy s.exc_info()) if su pplied, with argum ents func (fau lty function),
and path (concer ned file). This function fails when the files ar e Read Only .
Cr eate an archiv e file (eg. zip or tar) and retur ns its nam e. base_name is the nam e of the
file to cr eate, including the path, m inus any form at-specific extension. format is the
archiv e form at: one of zip, tar , bztar or gztar. root_dir is a directory that will be
the root dir ector y of the archiv e; ie. we ty pically chdir into root_dir befor e creating the
archiv e. base_dir is the directory where w e start archiv ing fr om ; ie. base_dir w ill be the
com m on prefix of all files and dir ector ies in the archiv e. root_dir and base_dir both
defau lt to the cu rrent dir ectory . owner and group ar e used when creating a tar archiv e.
By default, uses the cur rent ow ner and group. logger is an instance of logging.Logger .

(and also: copyfile, copymode, copystat, copy2)

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

Year (e.g. 1 993 )


Month [1 ,1 2 ]
Day [1 ,3 1 ]
Hou r [0,2 3 ]
Minute [0,59 ]
Second [0,61]; The 6 1 accounts for leap seconds and (the v ery rare)
double leap seconds.
Weekday [0,6 ], Monday is 0
Ju lian day [1 ,3 66 ]
Day light flag: 0, 1 or -1 ; -1 passed to mktime() w ill usually wor k

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.

Formatting in strftime() and strptime()


Di r ect iv e Mea n in g
%a
Locale's abbr ev iated weekday nam e.
%A
Locale's full w eekday nam e.
%b
Locale's abbr ev iated m onth nam e.
%B
Locale's full m onth nam e.
%c
Locale's appr opriate date and tim e r epresentation.
%d
Day of the m onth as a decim al num ber [01 ,3 1 ].
%f
Microsecond as a decim al num ber [0,9 99 999 ], zer o-padded on the left.
%H
Hou r (2 4-hour clock) as a decim al num ber [00,2 3 ].
%I
Hou r (1 2 -hou r clock) as a decim al num ber [01 ,1 2 ].
%j
Day of the y ear as a decim al num ber [001 ,3 66 ].
%m
Month as a decim al num ber [01 ,1 2 ].
%M
Minu te as a decim al nu m ber [00,59].
%p
Locale's equiv alent of either AM or PM.
%S
Second as a decim al num ber [00,61 ]. Yes, 61 !
%U
Week num ber of the y ear (Sunday as the first day of the w eek) as a decim al num ber [00,53 ]. All day s in a new y ear
%w
%W
%x
%X
%y
%Y
%Z
%z
%%

pr eceding the first Su nday ar e considered to be in week 0.


Weekday as a decim al nu m ber [0(Sunday ),6].
Week num ber of the y ear (Monday as the first day of the w eek) as a decim al num ber [00,53 ]. All day s in a new y ear
pr eceding the first Su nday ar e considered to be in week 0.
Locale's appr opriate date repr esentation.
Locale's appr opriate tim e representation.
Year without century as a decim al nu m ber [00,99 ].
Year with centu ry as a decim al num ber.
Tim e zone nam e (no char acters if no tim e zone exists).
UTC offset in the form + HHMM or -HHMM (em pty string if the date is naive).
A literal "%" character .

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

The str ing '01 2 3 4567 89 '.


Legal hexadecim al & octal digits.
Strings containing the appropriate characters, taking the curr ent locale into
account.
Strings containing Ascii characters.

Some string functions


Fu n ct i on

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

Returns a copy of string s with tabs expanded.


Returns the lowest/highest index in s where the substring sub is found such that sub is
w holly contained in s[start:end]. Retu rn -1 if sub not found.
Returns a copy of string s; left/right ju stified/centered in a field of giv en w idth, padded
w ith spaces or the giv en character. s is nev er truncated.
Returns a string that is (a copy of) s in lower case/u pper case.

low er/upper(s)
split(s[, sep=w hitespace[, maxsplit= 0]])
rsplit(s[, sep= whitespace[, maxsplit= 0]])

Returns a string that is (a copy of) s in lower case/u pper case.


Returns a list containing the w ords of the str ing s, using the string sep as a separator.
Sam e as split abov e but starts splitting from the end of string, e.g.
'A,B,C'.split(',', 1) == ['A', 'B,C'] but 'A,B,C'.rsplit(',', 1) ==
['A,B', 'C']

join(words[, sep= ' '])


replace(s, old, new[, maxsplit= 0]
str ip(s[, chars= None])

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)

Matches any character (including newline if DOTALL flag specified).


Matches star t of the string (of ev ery line in MULTILINE m ode).
Matches end of the string (of ev ery line in MULTILINE m ode).
0 or m ore of pr eceding r egular expr ession (as many as possible).
1 or m ore of preceding regu lar expression (as many as possible).
0 or 1 occurr ence of preceding regular expr ession.
Sam e as *, + and ? but m atches as few char acters as possible.
Matches fr om m to n repetitions of preceding RE.
Idem , attem pting to m atch as few repetitions as possible.
Defines char acter set: e.g. '[a-zA-Z]' to m atch all letters (see also \w \S).
Defines com plem ented character set: m atches if char is NOT in set.
Escapes special char s '*?+ &$|()' and intr oduces special sequ ences (see below). Due to Py thon string ru les, wr ite as '\\'
or r '\' in the patter n str ing.
Matches a litteral '\'; due to Py thon string r ules, w rite as '\\\\' in pattern string, or better u sing r aw string: r'\\'.
Specifies alternativ e: 'foo|bar' m atches 'foo' or 'bar'.
Matches any RE inside (), and delim its a group.
Idem bu t doesn't delim it a group (non capturing parenthesis).
Matches any RE inside (), and delim its a named group, (e.g. r'(?P< id> [a-zA-Z_]\w*)' defines a grou p nam ed id).
Matches w hatev er text was m atched by the earlier grou p nam ed name.
Matches if ... m atches next, but doesn't consu m e any of the string e.g. 'Isaac (?= Asim ov )' m atches 'Isaac' only if
follow ed by 'Asim ov '.
Matches if ... doesn't m atch next. Negativ e of (?= ...).
Matches if the cu rrent position in the string is pr eceded by a m atch for ... that ends at the curr ent position. This is
called a positive lookbehind assertion.
Matches if the cu rrent position in the string is not pr eceded by a m atch for .... This is called a negative lookbehind
assertion.
[2 .4 + ] group is either a nu m er ic grou p ID or a gr oup nam e defined w ith (?Pgroup...) earlier in the expression. If
the specified gr oup m atched, the regu lar expression pattern A will be tested against the string; if the group didn't
m atch, the patter n B will be u sed instead.
A com m ent; ignor ed.
letters is one or m ore of 'i','L', 'm ', 's', 'u', 'x'. Sets the corr esponding flags (re.I, r e.L, re.M, r e.S, re.U, r e.X) for the
entire RE. See the compile() function for equiv alent flags.

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

Exception w hen pattern string isn't a v alid regexp.

Functions
Fu n ct i on

com pile(pattern[,flags= 0])

Resu lt

Com piles a RE patter n str ing into a regular expression object.


Flags (com binable by |):
I o r IGNORECASE <=> (?i)

I o r IGNORECASE <=> (?i)


ca se in sen sit iv e m a t ch in g
L o r LOCALE <=> (?L)
m a k e \w , \W , \b, \B depen den t on t h e cu r r en t loc a le
M or MULTILINE <=> (?m )
m a t ch es ev er y n ew lin e a n d n ot on ly st a r t /en d of t h e w h ole st r in g
S o r DOTALL <=> (?s )
'.' m a t ch es A LL c h a r s, in c lu din g n ew lin e
U o r UNICODE <=> (?u)
Ma k e \w , \W , \b, a n d \B depen den t on t h e Un icode ch a r a ct er pr oper t ies da t a ba se.
X o r VERBOSE <=> (?x)
Ig n or es w h it espa ce ou tside ch a r a ct er set s

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])

su b(pattern, repl, string[, count= 0


[, flags]])
su bn(pattern, repl, string[, count= 0
[, flags]])

Regular Expression Object s


RE objects are returned by the compile function.
re object attributes
A t t r i bu t e

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

m atch(string[, pos][, endpos])

search(string[, pos][, endpos])

split(string[, maxsplit= 0])


findall(string[, pos[, endpos]])
finditer(string[, pos[, endpos]])
su b(repl, string[, count= 0])
su bn(repl, string[, count= 0])

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() .

Match object methods


Met h od

grou p([g1, g2, ...])

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

grou p([g1, g2, ...])

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)

Lexical scanners using regular expressions


There's an undocumented class in the re module called re.Scanner. The following recipee is from stackov erflow:
import re
scanner=re.Scanner([
(r"[0-9]+",
lambda scanner,token:("INTEGER", token)),
(r"[a-z_]+",
lambda scanner,token:("IDENTIFIER", token)),
(r"[,.]+",
lambda scanner,token:("PUNCTUATION", token)),
(r"\s+", None), # None == skip token.
])
results, remainder=scanner.scan("45 pigeons, 23 cows, 11 spiders.")
print results

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

3 .1 41 592 653 5897 9 3 1


2 .7 1 82 81 82 84590451

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

Returns the arc cosine (m easu red in radians) of x.


Returns the hy perbolic arc cosine (m easur ed in radians) of x.
Returns the arc sine (m easured in r adians) of x.
Returns the hy perbolic arc sine (m easu red in radians) of x.
Returns the arc tangent (m easu red in radians) of x.
Returns the arc tangent (m easu red in radians) of y/x. The result is betw een -pi and pi. Unlike atan(y/x) , the
signs of both x and y are considered.
Returns the hy perbolic arc tangent (m easur ed in radians) of x.
Returns the ceiling of x as a float. This is the sm allest integral v alue > = x.
Copies the sign bit of an IEEE 7 54 num ber, retu rning the absolu te v alue of x com bined with the sign bit of y,
e.g. copysign(1, -0.0) r eturns -1.0.
Returns the cosine of x (m easu red in radians).
Returns the hy perbolic cosine of x.
Conv erts angle x from radians to degrees.
Return the error function at x.
Return the com plem entary er ror fu nction at x.
Returns e raised to the power of x.
Return e**x - 1 with less loss of pr ecision at sm all floats than exp(x) - 1 .
Returns the absolute v alue of the float x.
r eturns n!
Returns the floor of x as a float. This is the largest integral v alu e < = x.
Returns fm od(x, y ), according to platform C. x % y m ay differ.
Returns the m antissa and exponent of x, as pair (m, e) . m is a float and e is an int, such that x = m * 2 .**e. If
x is 0, m and e are both 0. Else 0.5 < = abs(m ) < 1 .0.
Returns an accurate floating point sum of v alu es in iterable (assum es IEEE-7 54 floating point arithm etic).
Return the Gam m a function at x.
Returns the Euclidean distance sqrt(x*x + y*y) .
Returns True if x is infinite (positiv e or negativ e).
Returns True if x is not a num ber.
x * (2 **i)
Return the natu ral logarithm of the absolute v alu e of the Gam m a function at x.

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().

Compression of single file


Modu l e Descr i pt i on

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

Wor k w ith ZIP archiv es.


See the m ethod ZipFile.open for r eading a single file in the ar chiv e as a norm al file.
Read and w rite tar archiv e files.
The fu nction make_archive prov ides m eans for packaging a directory into a archiv e.

Lis t of mod ules a n d p a cka ges in b a s e d is tr ib ution


Built-ins and content of py thon Lib directory . The subdirectory Lib/site-packages contains platform-specific packages and
modules.
[Main distributions (Windows, Unix ), some OS specific modules may be missing]
Standard library modules
Oper a t i on

__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

Manipulate raw au dio data. 2 .5: Supports the a-LAW encoding.


Conv er sions to/from base64 transpor t encoding as per RFC-1 52 1 .
HTTP ser v er base class
"Bastionification" utility (control access to instance v ar s).
A generic Py thon debugger base class.
Conv er t between binar y and ASCII.
Macintosh binhex com pression/decom pression.
Bisection algorithm s.
(Optional) im prov ed BSD database interface [package].
BZ2 com pression.
Calendar printing functions.
Wraps the WWW Form s Com m on Gatew ay Inter face (CGI).
CGI-sav v y HTTP Serv er.
Traceback m anager for CGI scripts.
Read IFF chunked data.
Mathem atical fu nctions for com plex nu m ber s. See also m ath.
A generic class to bu ild line-or iented com m and interpreters.
Efficiently com pare files, boolean ou tcom e only .
Sam e, but caches 'stat' resu lts for speed.
Utilities needed to em ulate Py thon's interactiv e inter pr eter.
Lookup existing Unicode encodings and register new ones. 2 .5: suppor t for incr em ental codecs.
Utilities to com pile possibly incom plete Py thon sour ce code.
High-perform ance container dataty pes. 2 .4: The only dataty pe defined is a double-ended queue
deque . 2 .5: Ty pe deque has now a remove m ethod. New ty pe defaultdict . 2 .6 : New ty pe
namedtuple . Define many ABCs (Abstract Base Classes) like Container, Hashable, Iter able,
Sequence, Set...
Conv er sion fu nctions betw een RGB and other color sy stem s.
Execu te shell com m ands v ia os.popen [Unix].
Force "com pilation" of all .py files in a dir ectory .
Configur ation file parser (m u ch like w indows .ini files).
Utilities for with statem ent contexts.
HTTP state (cookies) m anagem ent.
Generic shallow and deep copy ing operations.
Helper to prov ide extensibility for m odules pickle/cPickle.
Faster, C im plem entation of pickle.
Faster, C im plem entation of pr ofile.
Fu nction to check Unix passw ords [Unix].
Faster, C im plem entation of StringIO.
Tools to read com m a-separ ated files (of v ar iations thereof). 2 .5: Sev eral enhancem ents.
"Foreign function" library for Py thon. Prov ides C com patible data ty pes, and allows to call functions
in dlls/shared libr aries. Can be used to wrap these libraries in pu re Py thon.
Ter m inal handling for character-cell display s [Unix/OS2/DOS only].
Im pr ov ed date/tim e ty pes ( date , time, datetime , timedelta). 2 .5: New m ethod
strptime(string, format) for class datetime . 2 .6 : strftime() new form at code %f expanding to
num ber of s.
(g)dbm -com patible interface to bsdhash.hashopen.
Decim al floating point arithm etic.
Tool for com paring sequences, and com puting the changes required to conv ert one into another.
2 .5: Im pr ov ed SequenceMatcher.get_matching_blocks() m ethod .
Sorted list of files in a dir , u sing a cache. Deprecated since 2 .6 .
Defines a class to build directory diff tools on.
By tecode disassem bler.
Package installation sy stem . 2 .5: Function setup enhanced w ith new key w ord par am eters
requires , provides , obsoletes , and download_url [PEP3 1 4].
Registers a m odule in the Py thon package index (Py PI). This com m and plugin adds the register
com m and to distu til scr ipts.

In 2 .7 m ov ed to separate m odu le sysconfig .


Call C functions in shar ed objects [Unix]. Depr ecated since 2 .6.
Unit testing fr am ew ork based on r unning exam ples em bedded in docstrings. 2 .5: New SKIP option.
New encoding ar g to testfile() fu nction.
Creation of self-docum enting XML-RPC serv ers, u sing py doc to create HTML API doc on the fly . 2 .5:
New attribu te rpc_paths .
Com m on oper ations on DOS pathnam es.
A dum b and slow bu t sim ple dbm clone.
Pr int py thon code that reconstru cts a v ariable.
Helpers to m ake it easier to wr ite code that u ses threads where suppor ted, bu t still runs on Py thon
v er sions without thread su pport. The dum m y m odu les sim ply r un the threads sequentially .
A package for parsing, handling, and gener ating em ail m essages. New v ersion 3 .0 dropped v arious
deprecated APIs and rem ov es su pport for Py thon v ersions ear lier than 2 .3 . 2 .5: Updated to v ersion
4.0.
New codecs: idna (IDNA strings), koi8_u (Ukranian), palmos (Palm OS 3 .5), puny code
(Pu ny code IDNA codec), string_escape (Py thon str ing escape codec: replaces non-printable chars
w/ Py thon-sty le string escapes). New codecs in 2 .4: HP Rom an8, ISO_8859-1 1 , ISO_8859-1 6 ,
PCTP-1 54, TIS-62 0; Chinese, Japanese and Kor ean codecs.
Standard err no sy stem sy m bols. The v alue of each sy m bol is the corresponding integer v alue.

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

Get infor m ation abou t liv e Py thon objects.


(new in 2 .6) Cor e tools for working with stream s [PEP 3 1 1 6]. Define Abstract Base Classes
RawIOBase (I/O operations: r ead, write, seek..), BufferedIOBase (bu ffering), and TextIOBase
(r eading & w riting strings).

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

iterkeyrefs() , keyrefs() , itervaluerefs() and valuerefs() .

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.

W orks pa ce explor a tion a n d id iom h in ts


dir(object)
dir()
if __name__ == '__main__':
main()
map(None, lst1, lst2, ...)
b = a[:]
b = list(a)
a,b,c = 1,2,3
for key, value in dic.items(): ...
if 1 < x <= 5: ...
for line in fileinput.input(): ...
_

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 -)

Type C-c ? when in python-mode for extensive help.


INDENTATION
Primarily for entering new code:
TAB
indent line appropriately
LFD
insert newline, then indent
DEL
reduce indentation, or delete single character
Primarily for reindenting existing code:
C-c :
guess py-indent-offset from file content; change locally
C-u C-c :
ditto, but change globally
C-c TAB reindent region to match its context
C-c <
shift region left by py-indent-offset
C-c >
shift region right by py-indent-offset
MARKING & MANIPULATING REGIONS OF CODE
C-c C-b
mark block of lines
M-C-h
mark smallest enclosing def
C-u M-C-h
mark smallest enclosing class
C-c #
comment out region of code
C-u C-c #
uncomment region of code
MOVING POINT
Cc C-p
C-c C-n
C-c C-u
M-C-a

move to statement preceding point


move to statement following point
move up to start of current block
move to start of def

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

Você também pode gostar