You are on page 1of 2

20102012 - Laurent Pointal Abrg v1.3.

0 - English
Licence Creative Commons Attribution 2
Python 3.2 Reference Card
Summary necessarily incomplete to keep on one paper sheet, see
http://docs.python.org/py3k.
Cheat Sheet Symbols
o!tional instructions " # re!eatable instructions"
$ immutable %ata" & or%ere% container '( non
or%ere%)" constant" variable" type" function *
.method" parameter" [,optional parameter]"
keyword" literal" module" file.
Introspection & Help
help([objet or "subject"])
id(objet) dir([object]) vars([object])
locals() globals()
Qualified Access
+e!arator . bet,een a namespace an% a name in
that s!ace. -ames!aces . ob/ect" class" 0unction"
mo%ule" !ac1age. E2am!les .
math.sin(math.pi) f.doc
MyClasse.nbObjects()
point.! rectangle.width()
ase !ypes
un%e0ine% $ . None
Boolean $. bool True 3 False
bool(!) 4 False i0 ! nul or em!t5
Integer $. int !"# $#%
binar5.b!! octal.o% he2a.&f'e
int(![,base]) .bit(length()
Floating $. float . $!'.)e$*
float(!) .as(integer(ratio()
Complex $. comple& j $!.)e*+,.*j
comple&(re[,img]) .real .imag
.conjugate()
String $&. str -- -toto- .toto.
...multiline toto...
str(!) repr(!)
Identifiers" #ariables & Assi$nment
Identifiers . [a-zA-Z_] 0ollo,e% b5 or one or
multi!le [a-zA-Z0-9_]" accent an% non-latin
al!habetical chars allo,e% 'but shoul% be
avoi%e%).
name / e!pression
name"0name#0name$ / se%uence
6 se%uence containing - items
name" / name#& / name' / e!pression
7 un!ac1ing se8uence. (irst01remain/se%uence
7 increment . name/name+e!pression
9 augmente% assignment . name+/e!pression
',ith other o!erators too)
7 %eletion . del nom
Identifiers Con%entions
:etails in PEP ; <+t5le =ui%e 0or P5thon>
A_CONSTANT u!!ercase
alocalvar lo,ercase ,ithout ?
a_global_var lo,ercase ,ith ?
a_function lo,ercase ,ith ?
a_!t"o# lo,ercase ,ith ?
ACla$$ title
An%&c!'tion%rror title ,ith Error at en%
ao#ul! lo,ercase rather ,ithout ?
a'ac(ag! lo,ercase rather ,ithout ?
Avoi% l O ) 'l min" o ma/" i ma/) alone.
_&&& internal usage
__&&& mo%i0ie% ?Class??222
__&&&__ s!cial reserve% name
&o$ical 'perations
a2b a2/b a3/b a3b a@b4a//b aAb4a4/b
not a a and b a or b 5e!pr6
7 combine% . !)2!2/'*
(aths
$a a+b a$b a1b a7b a
b
4a11b 5e!pr6
eucli%ian %ivision a@b.8Br 4 %/a77b et r/a8b
et %,r/divmod(a,b)
C2C4abs(!) 2
5
DE4pow(!,y[,)]) round(![,n])
6 0ollo,ing 0unctions3%ata in mo%ule math
e pi ceil(&) floor(!) trunc(!)
e
2
4e&p(!) log(!) *4s9rt(!)
cos(!) sin(!) tan(!) acos(!) asin(!)
atan(!) atan)(!,y) hypot(!,y)
cosh(!) sinh(!)
6 0ollo,ing 0unctions in mo%ule random
seed([!]) random() randint(a,b)
randrange([start],end[,step]) uniform(a,b)
choice(se%) shuffle(![,rnd]) sample(pop,k)
its (anipulations
',ith integers) a22b a33b a:b a;b a<b
Strin$
Escape . =
== 4 = =- 4 - =. 4 .
=n 4 ne, line =t 4 tab
=N>name? 4 unico%e name
=&hh 4 hh he2a =oo 4 oo octal
=uhhhh et =@hhhhhhhh 4 unico%e he2a hhhh
7 !re0i2 r" %isable = . r.=n. 4 =n
Formating . .>model?..format(data)
+,- ,-+.forat(/01)
+,2- ,0- ,0-+.forat(/09)
+,&- ,3-+.forat(3410&45)
+,06r- ,06$-+.forat(+t!&t7n+)
+,08b-,08o-,0-,08&-+.forat(200)
+,080.1f-,080./g-,08.2!-+.forat(2.95)
Operations
s1n 're!eat) s"+s# 'concatenate) 1/ +/
.split([sep[,n]]) .join(iterable)
.splitlines([keepend]) .partition(sep)
.replace(old,ne*[,n]) .find(s[, start[,end]])
.count(s[, start[,end]]) .inde&(s[, start[,end]])
.isdigit() * Co .lower() .upper()
.strip([chars])
.startswith(s[,start[,end]])
.endsswith(s[,start[,end]])
.encode([enc[, err]])
ord(c) chr(i)
Conditional )*pression
Evaluate% as a value.
e!pr" if condition else e!pr#
+lo, Control
6 statements blocs %elimite% b5 in%entation 'i%em
0unctions" classes" metho%s). Convention F
s!aces - tune e%itor.
Alternative If
if condition"A
G bloc1 e2ecute% i0 condition" is true
elif condition#A #
G bloc1 e2ecute% i0 condition# is true
elseA
G bloc1 e2ecute% i0 all con%itions are 0alse
Loop Over Sequence
for var in iterableA
G bloc1 e2ecute% ,ith var being successivel5
G each o0 the values in iterable
elseA
G e2ecute% a0ter" e2ce!t i0 e2it 0or loo! b5 brea1
7 var ,ith multi!le variables . for !0y0) in
7 var in%e2"valuer . for i0v in enumerate()
7 iterable : see +ontainers , -terables
Loop While
while conditionA
G bloc1 e2ecute% ,hile condition is true
elseA
G e2ecute% a0ter" e2ce!t i0 e2it ,hile loo! b5
brea1
Loop Brea . break
Hmme%iate e2it o0 the loo!" ,ithout going through else
bloc1.
Loop !ump . continue
Hmme%iate /um! at loo! start ,ith ne2t iteration.
Errors "rocessing# Exceptions
tryA
G bloc1 e2ecute% in normal case
e&cept e!c as eA #
G bloc1 e2ecute% i0 an error o0 t5!e e!c is
%etecte%
elseA
G bloc1 e2ecute% in case o0 normal e2it 0rom tr5
finallyA
G bloc1 e2ecute% in all case
7 e!c 0or n t5!es . e&cept (e!c"0e!c#0e!cn)
7 as e o!tional" 0etch e2ce!tion
I %etect s!eci0ic e2ce!tions 'e2. JalueError) an%
not generic ones 'e2. E2ce!tion).
$aising Exeptions 'error situation)
raise e!c([args])
raise 4 I !ro!agate e2ce!tion
+ome e2ce!tion classes . B&ception -
CrithmeticBrror - DeroEivisionBrror -
Fnde&Brror - GeyBrror - CttributeBrror
- FOBrror - FmportBrror - NameBrror -
Hynta&Brror - TypeBrror -
NotFmplementedBrror
%anaged Context
with managed') as v A
G Kloc1 e2ecute% in a manage% conte2t
+unction -efinition and Call
def (name(!,y./,0args,00k*args)A
G 0unction bloc1 or" i0 no co%e" pass
return rete!pression
!. sim!le !arameter
y. !arameter ,ith %e0ault value
args. variable !arameters b5 or%er 'tuple)
k*args. name% variable !arameters 'dict)
rete!pression. tuple 4 return multi!le values
Call
res @ (name(e!pr0param4e!pr0:tuple0::dict)
Anon&mous Functions
lambda !,yA e!pression
Se.uences & Inde*ation
6 0or an5 %irect access or%ere% container.
i
th
Item . !IiJ
Slice . !IstartAendJ !IstartAendAstepJ
6 i" start" end" step integers !ositive or negative
7 start3end missing 4 u! to start3en%
!/i0
-; -5 -9 -/ -1 -2
0 2 1 / 9 5
!
L M N O P Q
!/st1end0
0 2 1 / 9 5 ;
-; -5 -9 -/ -1 -2
%odification 'i0 se8uence is mo%i0iable)
!IiJ/e!pression!IstartAendJ/iterable
del !IiJ del !IstartAendJ
Containers & Iterables
An iterable !rovi%e values one a0ter the other. E2 .
containers" %ictionar5 vie,s" iterable ob/ets"
generator 0unctions
'enerators 'calculate values ,hen nee%e%)
range([start,]end[,step])
5 e!pr for var in iter # if cond 6
'eneric Operations
v in containeur v not in containeur
len(containeur) enumerate(iter[,start])
iter(o[,sent]) all(iter) any(iter)
filter((ct,iter) map((ct,iter,&)
ma&(iter) min(iter) sum(iter[,start])
reversed(se%) sorted(iter[,k][,rev])
Rn se8uences . .count(!) .inde&(![,i[,j]])
String $& . 'se8uence o0 chars)
7 c0. t5!es bytes" bytearray" memoryview to
%irectl5 mani!ulate b5tes 'Bnotation
b.bytes.).
List & . list IJ I!0-toto-0'.!*J
list(iterable) .append(!)
.e&tend(iterable) .insert(i,!) .pop([i])
.remove(!) .reverse() .sort()
I e!pr for var in iter # if cond J
(uple $& . tuple 56 5,0-&-0'"6 5!06
tuple(iterable) ,0-&-0'" !0
Set ( . set >!0-toto-0*)?
set(iterable) $( 4 froKenset(iterable)
.add(!) .remove(!) .discard(!)
.copy() .clear() .pop()
S4;" T4:" %i004$" s5m.%i004<" U42
;/ :/ $/ </
)ictionnar& 'associative arra5" ma!) ( . dict
>? >!A-one-0)A-two-?
dict(iterable) dict(a/)0b/*)
dict.fromkeys(se%[,val])
dIkJ/e!pr dIkJ del dIkJ
.update(iter) .keys() .values()
.items() .pop(k[,de(]) .popitem()
.get(k[,de(]) .setdefault(k[,de(])
.clear() .copy()
7 items" keys" values iterable <vie,s>.
Input2'utput & +iles
print(+&4+0![,y][,sep.][,end.][,(ile.])
input(.Cge L .) 4 str
7 e2!licit cast to int or float i0 nee%e%.
File . (/open(name[,mode][,encoding.&])
mode . -r- rea% '%e0ault) -w- ,rite -a- a!!en%
-+- rea% ,rite -b- binar5 mo%e &
encoding . -utf$M- -latin!- -ascii-&
.write(s) .read([n]) .readline()
.flush() .close() .readlines()
Loo! in lines .for line in ( 8&
Vanage% conte2t 'close) . with open() as (8
6 in mo%ule os 'see also os.path).
getcwd() chdir(path) listdir(path)
Comman% line !arameters in sys.argv
(odules & Pac3a$es
%odule . scri!t 0ile e2tension .py 'an% C com!ile%
mo%ules). Wile toto.py 4 mo%ule toto.
"acage . %irector5 ,ith 0ile __init__.py. Contains
mo%ule 0iles.
+earche% in the PXYZR-PAYZ" see sys.path list.
%odule Sample #
<6=u$r=bin='3t"on/
< -:- co#ing8 utf-> -:-
+++?o#ul! #ocu!ntation - cf @%@15A+++
< Bil!8 3o#ul!.'3
< Aut"or8 Co! Stu#!nt
< Fmport other modules0 functionsN
i'ort at"
fro ran#o i'ort $!!#0unifor
< Eefinition of constants and globals
?AD)?E? 4 9
l$tBil!$ 4 []
< Eefinition of functions and classes
#!f f(&)8
+++Bunction #ocu!ntation+++

cla$$ Conv!rt!r(obF!ct)8
+++Cla$$ #ocu!ntation+++
nb_conv 4 0 < cla$$ var
#!f __init__($!lf0a0b)8
+++init #ocu!ntation+++
$!lf.v_a 4 a < in$tanc! var

#!f action($!lf03)8
+++?!t"o# #ocu!ntation+++

< Module auto$test
if __na!__ 44 G__ain__G8
if f(1) 64 98 < 'robl!

%odules * +ames Imports
import mymondule
from mymodule import f012'-131
from mymodule import 1
from mymodule import f as fct
Yo limit 1 e00ect" %e0ine in mymodule .
all / I .f.0 .MCOFM@M.]
Hm!ort via !ac1age .
from os.path import dirname
Class -efinition
+!ecial metho%s" reserve% names ((&&&&((.
class ClassName([superclass])A
G class bloc1
classvariable 4 e!pression
def ((init(((sel([,params&])A
G initialiEation bloc1
sel(.instancevariable 4 e!pression
def ((del(((sel()A
G %estruction bloc1
Pstaticmethod G [9<%ecorator>
def fct([,params&])A
G static metho% 'callable ,ithout ob/ect)
%em,ership (ests
isinstance(obj0class)
isssubclass(subclass0parentclass)
'b4ects Creation
\se the class as a 0unction" !arameters are !asse%
to constructor ((init((.
obj / ClasseName(params&)
Special Con%ersion (ethods
def ((str(((sel()A
G return %is!la5 string
def ((repr(((sel()A
G return re!resentation string
def ((bytes(((sel()A
G return b5tes string ob/ect
def ((bool(((sel()A
G return a boolean
def ((format(((sel(0(ormatspec)A
G return a string 0ollo,ing s!eci0ie% 0ormat
Special Comparison (ehods
]eturn True" False or NotFmplemented.
!2y 4 def ((lt(((sel(0y)A
!2/y 4 def ((le(((sel(0y)A
!//y 4 def ((e9(((sel(0y)A
!4/y 4 def ((ne(((sel(0y)A
!3y 4 def ((gt(((sel(0y)A
!3/y 4 def ((ge(((sel(0y)A
Special 'perations (ethods
]eturn a ne, ob/ect o0 the class" containing the
o!eration result" or NotFmplemented i0 cannot
,or1 ,ith given y argument.
! 4 sel(
!+y 4 def ((add(((sel(0y)A
!$y 4 def ((sub(((sel(0y)A
!1y 4 def ((mul(((sel(0y)A
!7y 4 def ((truediv(((sel(0y)A
!77y 4 def ((floordiv(((sel(0y)A
!8y 4 def ((mod(((sel(0y)A
divmod(!0y) 4 def ((divmod(((sel(0y)A
!11y 4 def ((pow(((sel(0y)A
pow(!0y0)) 4 def ((pow(((sel(0y0))A
!22y 4 def ((lshift(((sel(0y)A
!33y 4 def ((rshift(((sel(0y)A
!:y 4 def ((and(((sel(0y)A
!;y 4 def ((or(((sel(0y)A
!<y 4 def ((&or(((sel(0y)A
$! 4 def ((neg(((sel()A
+! 4 def ((pos(((sel()A
abs(!) 4 def ((abs(((sel()A
Q! 4 def ((invert(((sel()A
Wollo,ing metho%s calle% a0ter" on y i0 ! %on^t
su!!ort re8uire% o!eration.
y 4 sel(
!+y 4 def ((radd(((sel(0!)A
!$y 4 def ((rsub(((sel(0!)A
!1y 4 def ((rmul(((sel(0!)A
!7y 4 def ((rtruediv(((sel(0!)A
!77y 4 def ((rfloordiv(((sel(0!)A
!8y 4 def ((rmod(((sel(0!)A
divmod(!0y) 4 def ((rdivmod(((sel(0!)A
!11y 4 def ((rpow(((sel(0!)A
!22y 4 def ((rlshift(((sel(0!)A
!33y 4 def ((rrshift(((sel(0!)A
!:y 4 def ((rand(((sel(0!)A
!;y 4 def ((ror(((sel(0!)A
!<y 4 def ((r&or(((sel("!) A
Special Au$mented Assi$nment (ethods
Vo%i05 sel( ob/ect on ,hich the5 are a!!lie%.
! 4 sel(
!+/y 4 def ((iadd(((sel(0y)A
!$/y 4 def ((isub(((sel(0y)A
!1/y 4 def ((imul(((sel(0y)A
!7/y 4 def ((itruediv(((sel(0y)A
!77/y 4 def ((ifloordiv(((sel(0y)A
!8/y 4 def ((imod(((sel(0y)A
!11/y 4 def ((ipow(((sel(0y)A
!22/y 4 def ((ilshift(((sel(0y)A
!33/y 4 def ((irshift(((sel(0y)A
!:/y 4 def ((iand(((sel(0y)A
!;/y 4 def ((ior(((sel(0y)A
!</y 4 def ((i&or(((sel(0y)A
Special 5umerical Con%ersion (ethods
]eturn the converte% value.
! 4 sel(
comple&(!) 4 def ((comple&(((sel()A
int(!) 4 def ((int(((sel()A
float(!) 4 def ((float(((sel()A
round(!0n) 4 def ((round(((sel(0n)A
def ((inde&(((sel()A
G return an int usable as in%e2
Special Attribute Access (ethods
Access ,ith obj.name. E2ce!tion
CttributeBrror i0 attribute not 0oun%.
obj 4 sel(
def ((getattr(((sel(0name)A
G calle% i0 name not 0oun% as e2isting attribute
def ((getattribute(((sel(0name)A
G calle% in all case o0 name access.
def ((setattr(((sel(0name0valeur)A
def ((delattr(((sel(0name)A
def ((dir(((sel()A G return a list
Accessors
"ropert&
class C(object)A
def get&(sel()A
def set&(sel(0value)A
def del&(sel()A
! 4 property(get&0set&0del&0.doc&.)
< +im!ler" accessor to y" ,ith %ecorators
Pproperty
def y(sel()A G rea%
...docy...
Py.setter
def y(sel(0valeur)A G mo%i0ication
Py.deleter
def y(sel()A G %eletion
)escriptors "rotocol
o.& 4 def ((get(((sel(0o0classedeo)A
o.!/v 4 def ((set(((sel(0o0v)A
del o.! 4 def ((delete(('sel("o)A
Special +unction Call (ethod
\se an ob/ect as i0 it ,as a 0unction 'callable) .
o5params64 def ((call(((sel([,params&])A
Hash Special (ethod
Wor e00icient storage in dict an% set.
hash(o) 4 def ((hash(((sel()8
:e0ine to None i0 ob/ect not hashable.
Special Container (ethods
o 4 sel(
len(o) 4 def ((len(((sel()A
oIkeyJ 4 def ((getitem(((sel(0key)A
oIkeyJ/v 4 def ((setitem(((sel(0key0v)A
del oIkeyJ 4 def ((delitem(((sel(0key)A
for i in o. 4 def ((iter(((sel()A
G return a ne, iterator on the container
reversed(o) 4 def ((reversed(((sel()A
2 in o 4 def ((contains(((sel(0!)A
Wor notation IstartAendAstepJ" a slice ob/ect is given
to container metho%s as value 0or key !arameter.
Slice$. slice(start0end0step)
.start .stop .step .indices(lentgh)
Special Iterator (ethods
def ((iter(((sel()AG return sel0
def ((ne&t(((sel()AG return ne2t item
H0 no more item" raise e2ce!tion HtopFteration.
Special (ana$ed Conte*t (ethods
\se% 0or with statement.
def ((enter(((sel()A
G calle% at entr5 in the manage% conte2t
G return value use% 0or conte2t^ as variable
def ((e&it(((sel(0etype0eval0tb)A
G calle% at e2it o0 manage% conte2t
Special (etaclass (ethods
prepare 4 callable
def ((new(((cls[,params&])A
G allocation an% return a ne, cls ob/ect
isinstance'o"cls)
4 def ((instancecheck(('cls"o)A
isssubclass(subclass0cls)
4 def ((subclasscheck(('cls"subclass)A
6enerators
Calculate values ,hen nee%e% 'e2.. range).
=enerator 0unctions" contains a statement yield.
yield e!pression
yield from squence
variable @ 'yield e!pression) transmission o0
values to the generator.
H0 no more item" raise e2ce!tion HtopFteration.
'enerator Function Control
generator.((ne&t((()
generator.send(value)
generator.throw(type[,value[,traceback]])
generator.close()

You might also like