You are on page 1of 2

20102012 - Laurent Pointal Abrg v1.3.

0 - English Licence Creative Commons Attribution 2 Cheat Sheet Symbols

Python 3.2 Reference Card


its (anipulations

Summary necessarily incomplete to keep on one paper sheet, see http://docs.python.org/py3k.

o!tional instructions " # re!eatable instructions" ',ith integers) a22b a33b a:b a;b a<b $ immutable %ata" & or%ere% container '( non Strin$ or%ere%)" constant" variable" type" function * Escape . = .method" parameter" [,optional parameter]" == 4 = =- 4 =. 4 . keyword" literal" module" file. =n 4 ne, line =t 4 tab Introspection & Help =N>name? 4 unico%e name help([objet or "subject"]) =&hh 4 hh he2a = oo 4 oo octal id(objet) dir([object]) vars([object]) =uhhhh et =@hhhhhhhh 4 unico%e he2a hhhh locals() globals() 7 !re0i2 r" %isable = . r.=n. 4 =n Qualified Access Formating . .>model?..format(data) +e!arator . bet,een a namespace an% a name in +,- ,-+.for at(/01) +,2- ,0- ,0-+.for at(/09) that s!ace. -ames!aces . ob/ect" class" 0unction" +,&- ,3-+.for at(3410&45) mo%ule" !ac1age. E2am!les . +,06r- ,06$-+.for at(+t!&t7n+) +,08b-,08o-,0-,08&-+.for at(200) math.sin(math.pi) f. doc

%anaged Context with managed') as v

Fnde&Brror - GeyBrror - CttributeBrror - FOBrror - FmportBrror - NameBrror Hynta&Brror - TypeBrror NotFmplementedBrror

!. sim!le !arameter y. !arameter ,ith %e0ault value args. variable !arameters b5 or%er 'tuple) k*args. name% variable !arameters 'dict) +,080.1f-,080./g-,08.2!-+.for at(2.95) ret e!pression. tuple 4 return multi!le values MyClasse.nbObjects() Operations point.! rectangle.width() Call s1n 're!eat) s"+s# 'concatenate) 1/ +/ ase !ypes res @ (name(e!pr0param4e!pr0:tuple0::dict) .split([sep[,n]]) .join(iterable) Anon&mous Functions un%e0ine% $ . None .splitlines([keepend]) .partition(sep) lambda !,yA e!pression Boolean $. bool True 3 False .replace(old,ne*[,n]) .find(s[, start[,end]]) bool(!) 4 False i0 ! nul or em!t5 Se.uences & Inde*ation .count(s[, start[,end]]) .inde&(s[, start[,end]]) Integer $. int !"# $#% 6 0or an5 %irect access or%ere% container. .isdigit() * Co .lower() .upper() binar5. b! ! octal. o% he2a. &f'e ith Item . !IiJ .strip([chars]) int(![,base]) .bit(length() .startswith(s[,start[,end]]) Slice . !IstartAendJ !IstartAendAstepJ Floating $. float . $!'.)e$* .endsswith(s[,start[,end]]) 6 i" start" end" step integers !ositive or negative float(!) .as(integer(ratio() .encode([enc[, err]]) 7 start3end missing 4 u! to start3en% Complex $. comple& j $!.)e*+,.*j ord(c) chr(i) -; -5 -9 -/ -1 -2 comple&(re[,img]) .real .imag !/i0 Conditional )*pression 0 2 1 / 9 5 .conjugate() String $&. str --toto.toto. Evaluate% as a value. L M N O P Q ! ...multiline toto... e!pr" if condition else e!pr# str(!) repr(!) 0 2 1 / 9 5 ; +lo, Control !/st1end0 Identifiers" #ariables & Assi$nment -; -5 -9 -/ -1 -2 6 statements blocs %elimite% b5 in%entation 'i%em Identifiers . [a-zA-Z_] 0ollo,e% b5 or one or 0unctions" classes" metho%s). Convention F %odification 'i0 se8uence is mo%i0iable) multi!le [a-zA-Z0-9_]" accent an% non-latin s!aces - tune e%itor. !IiJ/e!pression!IstartAendJ/iterable al!habetical chars allo,e% 'but shoul% be Alternative If del !IiJ del !IstartAendJ avoi%e%). if condition"A Containers & Iterables name / e!pression G bloc1 e2ecute% i0 condition" is true An iterable !rovi%e values one a0ter the other. E2 . name"0name#0name$ / se%uence elif condition#A # containers" %ictionar5 vie,s" iterable ob/ets" 6 se%uence containing - items G bloc1 e2ecute% i0 condition# is true generator 0unctions name" / name#& / name' / e!pression elseA 'enerators 'calculate values ,hen nee%e%) 7 un!ac1ing se8uence. (irst01remain/se%uence G bloc1 e2ecute% i0 all con%itions are 0alse range([start,]end[,step]) 7 increment . name/name+e!pression Loop Over Sequence 5 e!pr for var in iter # if cond 6 9 augmente% assignment . name+/e!pression for var in iterableA 'eneric Operations ',ith other o!erators too) G bloc1 e2ecute% ,ith var being successivel5 v in containeur v not in containeur 7 %eletion . del nom G each o0 the values in iterable len(containeur) enumerate(iter[,start]) elseA Identifiers Con%entions iter(o[,sent]) all(iter) any(iter) G e2ecute% a0ter" e2ce!t i0 e2it 0or loo! b5 brea1 :etails in PEP ; <+t5le =ui%e 0or P5thon> filter((ct,iter) map((ct,iter,&) 7 var ,ith multi!le variables . for !0y0) in A_CONSTANT u!!ercase ma&(iter) min(iter) sum(iter[,start]) 7 var in%e2"valuer . for i0v in enumerate() reversed(se%) sorted(iter[,k][,rev]) alocalvar lo,ercase ,ithout ? a_global_var lo,ercase ,ith ? 7 iterable : see +ontainers , -terables Rn se8uences . .count(!) .inde&(![,i[,j]]) a_function lo,ercase ,ith ? Loop While String $& . 'se8uence o0 chars) a_ !t"o# lo,ercase ,ith ? while conditionA 7 c0. t5!es bytes" bytearray" memoryview to ACla$$ title %irectl5 mani!ulate b5tes 'Bnotation G bloc1 e2ecute% ,hile condition is true An%&c!'tion%rror title ,ith Error at en% b.bytes.). elseA a o#ul! lo,ercase rather ,ithout ? G e2ecute% a0ter" e2ce!t i0 e2it ,hile loo! b5 List & . list IJ I!0-toto-0'.!*J a'ac(ag! lo,ercase rather ,ithout ? brea1 list(iterable) .append(!) Avoi% l O ) 'l min" o ma/" i ma/) alone. Loop Brea . break .e&tend(iterable) .insert(i,!) .pop([i]) _&&& internal usage Hmme%iate e2it o0 the loo!" ,ithout going through else .remove(!) .reverse() .sort() __&&& mo%i0ie% ?Class??222 bloc1. I e!pr for var in iter # if cond J __&&&__ s!cial reserve% name Loop !ump . continue (uple $& . tuple 56 5,0-&-0'"6 5!06 &o$ical 'perations Hmme%iate /um! at loo! start ,ith ne2t iteration. tuple(iterable) ,0-&-0'" !0 a2b a2/b a3/b a3b a@b4a//b aAb4a4/b Errors "rocessing# Exceptions Set ( . set >!0-toto-0*)? tryA not a a and b a or b 5e!pr6 set(iterable) $( 4 froKenset(iterable) G bloc1 e2ecute% in normal case .add(!) .remove(!) .discard(!) 7 combine% . !)2!2/'* e&cept e!c as eA # .copy() .clear() .pop() (aths S4;" T4:" %i004$" s5m.%i004<" U42 G bloc1 e2ecute% i0 an error o0 t5!e e!c is $a a+b a$b a1b a7b ab4a11b 5e!pr6 ;/ :/ $/ </ %etecte% eucli%ian %ivision a@b.8Br 4 %/a77b et r/a8b elseA )ictionnar& 'associative arra5" ma!) ( . dict et %,r/divmod(a,b) G bloc1 e2ecute% in case o0 normal e2it 0rom tr5 >? >!A-one-0)A-two-? finallyA dict(iterable) dict(a/)0b/*) C2C4abs(!) 25DE4pow(!,y[,)]) round(![,n]) G bloc1 e2ecute% in all case dict.fromkeys(se%[,val]) 6 0ollo,ing 0unctions3%ata in mo%ule math 7 e!c 0or n t5!es . e&cept (e!c"0e!c#0e!cn) dIkJ/e!pr dIkJ del dIkJ e pi ceil(&) floor(!) trunc(!) .update(iter) .keys() .values() 7 as e o!tional" 0etch e2ce!tion e24e&p(!) log(!) *4s9rt(!) .items() .pop(k[,de(]) .popitem() I %etect s!eci0ic e2ce!tions 'e2. JalueError) an% cos(!) sin(!) tan(!) acos(!) asin(!) .get(k[,de(]) .setdefault(k[,de(]) not generic ones 'e2. E2ce!tion). atan(!) atan)(!,y) hypot(!,y) .clear() .copy() $aising Exeptions 'error situation) cosh(!) sinh(!) 7 items" keys" values iterable <vie,s>. raise e!c([args]) 6 0ollo,ing 0unctions in mo%ule random Input2'utput & +iles raise 4 I !ro!agate e2ce!tion seed([!]) random() randint(a,b) print (+&4+0 ![,y ][,sep.][,end.][,(ile.]) +ome e2ce!tion classes . B&ception randrange([start],end[,step]) uniform(a,b) input(.Cge L .) 4 str CrithmeticBrror DeroEivisionBrror choice(se%) shuffle(![,rnd]) sample(pop,k)

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 ret e!pression

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. "ac age . %irector5 ,ith 0ile __init__.py. Contains

def ((format(((sel(0(ormat spec)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

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&

]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 mo%ule 0iles. !$y 4 def ((sub(((sel(0y)A +earche% in the PXYZR-PAYZ" see sys.path list. !1y 4 def ((mul(((sel(0y)A %odule Sample # !7y 4 def ((truediv(((sel(0y)A <6=u$r=bin='3t"on/ !77y 4 def ((floordiv(((sel(0y)A < -:- co#ing8 utf-> -:+++?o#ul! #ocu !ntation - cf @%@15A+++ !8y 4 def ((mod(((sel(0y)A < Bil!8 3 o#ul!.'3 divmod(!0y) 4 def ((divmod(((sel(0y)A < Aut"or8 Co! Stu#!nt !11y 4 def ((pow(((sel(0y)A < Fmport other modules0 functionsN i 'ort at" pow(!0y0)) 4 def ((pow(((sel(0y0))A fro ran#o i 'ort $!!#0unifor !22y 4 def ((lshift(((sel(0y)A < Eefinition of constants and globals !33y 4 def ((rshift(((sel(0y)A ?AD)?E? 4 9 l$tBil!$ 4 [] !:y 4 def ((and(((sel(0y)A < Eefinition of functions and classes !;y 4 def ((or(((sel(0y)A #!f f(&)8 !<y 4 def ((&or(((sel(0y)A +++Bunction #ocu !ntation+++ $! 4 def ((neg(((sel()A cla$$ Conv!rt!r(obF!ct)8 +! 4 def ((pos(((sel()A +++Cla$$ #ocu !ntation+++ abs(!) 4 def ((abs(((sel()A nb_conv 4 0 < cla$$ var #!f __init__($!lf0a0b)8 Q! 4 def ((invert(((sel()A +++init #ocu !ntation+++ Wollo,ing metho%s calle% a0ter" on y i0 ! %on^t $!lf.v_a 4 a < in$tanc! var su!!ort re8uire% o!eration. #!f action($!lf03)8 y 4 sel( +++?!t"o# #ocu !ntation+++ !+y 4 def ((radd(((sel(0!)A !$y 4 def ((rsub(((sel(0!)A < Module auto$test if __na !__ 44 G__ ain__G8 !1y 4 def ((rmul(((sel(0!)A if f(1) 64 98 < 'robl! !7y 4 def ((rtruediv(((sel(0!)A !77y 4 def ((rfloordiv(((sel(0!)A %odules * +ames Imports !8y 4 def ((rmod(((sel(0!)A import mymondule divmod(!0y) 4 def ((rdivmod(((sel(0!)A from mymodule import f012'-131 from mymodule import 1 !11y 4 def ((rpow(((sel(0!)A from mymodule import f as fct !22y 4 def ((rlshift(((sel(0!)A Yo limit 1 e00ect" %e0ine in mymodule . !33y 4 def ((rrshift(((sel(0!)A all / I .f.0 .MCOFM@M.] !:y 4 def ((rand(((sel(0!)A Hm!ort via !ac1age . !;y 4 def ((ror(((sel(0!)A from os.path import dirname !<y 4 def ((r&or(((sel("!) A Class -efinition +!ecial metho%s" reserve% names ((&&&&((. class ClassName([superclass])A
G class bloc1 Special Au$mented Assi$nment (ethods

)escriptors "rotocol o.& 4 def ((get(((sel(0o0classe de o)A o.!/v 4 def ((set(((sel(0o0v)A del o.! 4 def ((delete(('sel("o)A
Special +unction Call (ethod

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

\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

class variable 4 e!pression def ((init(((sel([,params&])A

%em,ership (ests isinstance(obj0class) isssubclass(subclass0parentclass)


'b4ects Creation

G initialiEation bloc1 sel(.instance variable 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)

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

\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

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

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

obj 4 sel(

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