Python 2.4 Quick Reference Card
Python 2.4 Quick Reference Card
3tyle $ keyword function7method type replaced_expression variable literal module module_filename language_syntax :otation $ f() return value f()return nothing (procedure) [x] for a list of x data9 (x) for a tuple of x data9 &ay ha%e x{n} n ti&e x data.
Types basestring1 bool buffer complex dict exception file float frozenset global int list long object set slice str tuple type unicode xrange , (a e trin" i %irtual upercla of tr and unicode. 2hi doc u e string 0hen unicode and str can apply. Func !"ns Con tructor function of (uiltin type are directly acce i(le in (uiltin . __import__ abs apply1 callable chr classmethod cmp coerce compile delattr dir divmod enumerate eval execfile filter getattr globals hasattr hash help hex id input intern2 isinstance issubclass iter len locals map max min oct open ord pow property range raw_input reduce reload repr reversed round set setattr sorted staticmethod sum super unichr vars zip , = e fCTar" 9TTkar" D in place of applyCf9ar" 9kar" D. 2 <onPt u e intern.
ENVIRONMENT VARIABLES
PJ2G#:C43*#/ PJ2G#:<*1=I PJ2G#:G#;* no ca e di tinction in &odulefile mapping K -d co&&and-line option ;odify tandard Python li( prefi. and e.ec prefi. location . = e <prefix>[:<execprefix>]. , PJ2G#:6:3P*C2 K -i co&&and-line option , PJ2G#:#P26;6L* K -# co&&and-line option PYTHONPATH <irectorie 0here Python earch 0hen i&portin" &odule 7packa"e . 3eparator $ Cpo i.D or M C0indo0 D. =nder 0indo0 u e re"i try G/L;N3of0areNO. PJ2G#:324R2=P -ile to load at (e"inin" of interacti%e e ion . , PJ2G#:=:1=--*R*< K -u co&&and-line option , PJ2G#:+*R1#3* K -% co&&and-line option , 6f et to non-e&pty %alue.
, ,
CARDS CONTENT
*n%iron&ent +aria(le ............................, Co&&and-line #ption ............................, -ile *.ten ion ......................................., Lan"ua"e /ey0ord ................................, 1uiltin ...................................................., 2ype ..................................................., -unction ............................................, 3tate&ent .............................................., 1lock ................................................., 4 i"n&ent 3hortcut ........................., Con ole 5 6nteracti%e 6nput7#utput.........2 #(8ect 9 :a&e and :a&e pace ...........2 6dentifier ............................................2 #(8ect and :a&e 9 Reference Countin".............................................2 ;uta(le76&&uta(le #(8ect ...............2 :a&e pace .......................................2 Con tant 9 *nu&eration ...................2 -lo0 Control............................................2 Condition............................................2 Loop...................................... ..............2 -unction 7ðod e.it......................2 *.ception ..........................................2 6tera(le Protocol.................................2 6nterpretation 7 *.ecution.......................2 -unction <efinition 5 = a"e.................2 Para&eter 7 Return %alue..................2 La&(da function ...............................2 Calla(le #(8ect ..................................2 Callin" -unction .................................2 -unction Control................................> <ecorator ..........................................> 2ype 7Cla e 5 #(8ect ..........................> Cla <efinition...................................> #(8ect Creation...................................> Cla e 5 #(8ect Relation ...............> 4ttri(ute ;anipulation......................> 3pecial ;ethod .................................> <e criptor protocol...........................> Copyin" #(8ect ..................................> 6ntro pection.......................................> ;odule and Packa"e ............................> 3ource encodin" ...............................> 3pecial 4ttri(ute ...............................> ;ain *.ecution 7 3cript Para&eter ........> #perator ................................................4 Priority................................................4 4rith&etic #perator ..........................4 Co&pari on #perator ........................4 #perator a -unction .......................4 1oolean ..................................................4 :u&(er ..................................................4 #perator ............................................4 -unction ............................................4 1it Le%el #peration ................................5 #perator ............................................5 3trin" ................................................... ..5 * cape e?uence ..............................5 =nicode trin" ...................................5 ;ethod and -unction .......................5 -or&atin"...........................................6 Con tant ............................................6 Re"ular *.pre ion ...........................6 [email protected] ;ultilin"ual 3upport............................A Container ............................................. ..B #peration on Container ...................B Copyin" Container ............................B #%erridin" Container #peration ......B 3e?uence ...............................................B Li t 5 2uple .................................... ..B #peration on 3e?uence ...................B 6nde.in"...................................... ........B #peration on &uta(le e?uence .....B #%erridin" 3e?uence #peration ......B ;appin" Cdictionarie D...........................B #peration on ;appin" .....................B #%erridin" ;appin" #peration ..........B #ther ;appin" ..................................B 3et .........................................................E #peration on 3et .............................E #ther Container 3tructure 9 4l"orith& E 4rray............................................. ......E Queue.................................................E Priority Queue ...................................E 3orted Li t...........................................E 6teration 2ool .....................................E <ate 5 2i&e............................................E ;odule ti&e........................................E ;odule dateti&e...............................,0 ;odule ti&eit....................................,0 #ther ;odule ..................................,0 -ile .......................................................,0 -ile #(8ect .......................................,0 Lo0-le%el -ile ...................................,0 Pipe .................................................,0 6n-&e&ory -ile ................................,0 -ile 6nfor&ation ..............................,, 2er&inal #peration ..........................,, 2e&porary -ile .................................,, Path ;anipulation ...........................,, <irectorie ........................................,, 3pecial -ile ......................................,2 Copyin"9 ;o%in"9 Re&o%in".............,2 *ncoded -ile .................................... ,2 3eriali@ation......................................,2 Per i tence.......................................,2 Confi"uration -ile ............................,2 *.ception .............................................,2 3tandard *.ception Cla e .............,2 Farnin" ...........................................,> *.ception Proce in"......................,> *ncodin" - <ecodin".............................,> 2hread 5 3ynchroni@ation...................,> 2hreadin" -unction .........................,> 2hread .............................................,> ;utual *.clu ion...............................,> *%ent ...............................................,> 3e&aphore ......................................,> Condition +aria(le ...........................,> 3ynchroni@ed Queue .......................,> Proce ..................................................,> Current Proce .................................,> 3i"nal Gandlin".................................,4 3i&ple *.ternal Proce Control.......,4 4d%anced *.ternal Proce Control. .,5 H;L Proce in".....................................,5 34H - *%ent-dri%en............................,5 <#; - 6n-&e&ory 2ree......................,6 <ata(a e .............................................,A Ieneric acce to <1;- tyle <1 .....,A 3tandard <1 4P6 for 3QL data(a e .,A 2ool ......................................................,B
STATEMENTS
#ne tate&ent per line,. Can continue on ne.t line if an e.pre ion or a trin" i not fini hed C ( [ { """ ''' not clo edD9 or 0ith a \ at end of line. Char # tart co&&ent up to end of line. pass assert expr[,message] del name[9] print [>>obj,][expr[9][,] exec expr [in globals [9 locals]] fctC[expr[,]],[name=expr[,]] [,*args][,**k args]D
name[,] = expr
,
COMMAND-LINE OPTIONS
python [-d*hi#Q3tu=%+F.] [-c cmd | -& mod | file | -] [args] -d #utput de(u""in" info fro& par er. -* 6"nore en%iron&ent %aria(le . -h Print help and e.it. -i -orce interacti%e &ode 0ith pro&pt Ce%en after cript e.ecutionD. -# #pti&i@e "enerated (ytecode9 re&o%e assert check . -## 4 -# and re&o%e docu&entation trin" . -Q arg <i%i ion option9 arg in 'oldCdefaultD9warn9warnall9new). -3 <onPt i&port ite.py definition &odule. -t Farn incon i tent ta(7 pace u a"e C-tt e.it 0ith errorD. -u = e un(uffered (inary output for tdout and tderr. -= -orce u e of unicode literal for trin" . -% 2race i&port . -+ Print %er ion nu&(er and e.it. -F arg *&it 0arnin" for arg Qaction$&e a"e$cate"ory$&odule$linenoQ -. 3kip fir t line of ource Cfort non-=ni. for& of RSc&dD. -c cmd *.ecute cmd. -& mod 3earch &odule mod in y .path and run it a &ain cript. file Python cript file to e.ecute. args Co&&and-line ar"u&ent for cmd7file9 a%aila(le in sys.argv[1:].
:ull tate&ent. 4 ertion check e.pre ion true. Re&o%e na&e o(8ect (indin". Frite expr to sys.stdout2. *.ecute expr in na&e pace . Call any calla(le o(8ect fct 0ith "i%en ar"u&ent C ee -unction <efinition 5 = a"e - p2D. 4 i"n&ent operator>.
;ultiple tate&ent on a&e line u in" ; eparator - a%oid if not nece ary. 2 Frite to any pecified o(8ect follo0in" file interface C0rite ðodD. Frite pace (et0een e.pre ion 9 line-return at end of line e.cept 0ith a final ,. > Left part na&e can (e container e.pre ion. 6f e.pr i a e?uence of &ultiple %alue 9 can unpack into &ultiple na&e . Can ha%e &ultiple a i"n&ent of a&e %alue on a&e line $ a K ( K c K e.pr. #ther tate&ent Cloop 9 condition D introduced in re pecti%e part .
FILES EXTENSIONS
.pyK ource9 .pycK(ytecode9 .pyoK(ytecode opti&i@ed9 .pydK(inary &odule9 .dll7.soKdyna&ic li(rary. .pywK ource a ociated to python0.e.e on Findo0 platfor&9 to run 0ithout openin" a con ole.
LANGUAGE KEYWORDS
Li t of key0ord in tandard &odule keyword. and as1 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 yield , not re er%ed9 (ut a%oid to redefine it. <onPt redefine the e con tant $ None9 True9 False.
B#"c$s 4 : (et0een tate&ent define dependant tate&ent 9 0ritten on a&e line or 0ritten on follo0in" lineC D 0ith deeper indentation. 1lock of tate&ent are i&ply line at a&e indentation le%el. if x<=0 : return 1 if asin(v)>pi/4 : a = pi/2 b = -pi/2 else : a = asin(v) b = pi/2-a 3tate&ent continuation line donPt care indentation. 2o a%oid pro(le& 9 confi"ure your editor to u e 4 pace in place of ta( . Ass!%n&en S'"( cu s a -= b a //= b a %= b a &= b a |= b
a += b a *= b a **= b a ^= b a /= b a >>= b a <<= b
BUILTINS
4%aila(le directly e%ery0here 0ith no pecific i&port. <efined al o in &odule __builtins__. 1b
1a
fro& enclo in" definition 9 then "lo(al 9 then (uiltin . #ut-of- cope na&e u e the dotted attri(ute notation x.y C&ay(e x.y.z.tD 0here x i a na&e %i i(le 0ithin the current cope. Cla na&e pace na&e defined in a cla Ccla &e&(er D. #(8ect na&e pace na&e u a(le 0ith object.name notation Cattri(ute 9 ðod D. :a&e pace can (e ne ted9 inner na&e pace hiddin" identical na&e fro& outer na&e pace . dir([object]) list" names defined in object namespace# vars([object]) dict$" identifier"value of object as a namespace# # if o(8ect not pecified u e neare t na&e pace Clocal D. $ &u t not (e &odified.
enumerate(iterable) iterator returning tuples (index%value) from iterable Iterators Objects Interface next(self) next item# __iter__(self) iterator object itself , Fhen reach end of collection9 rai e StopIteration e.ception on u( e?uent call Cie. iterator u a(le only one ti&e on a collectionD. Generators -unction retainin" their tate (et0een t0o call . Return %alue u in" yield. 3top "eneration %ia i&ple return or %ia raise StopIteration. ,D (uild "enerator fro& function $ gen=generatorfct(args) 2D u e gen.nextCD %alue until StopIteration i rai ed. Ienerator itera(le e.pre ion 0ith $ (x for x in iterable where condD Operations with/on Iterable 3ee #peration on Container CpBD. 3ee 6teration 2ool CpED.
C"ns 1n s, Enu&e(1 !"ns = e upperca e and U for con tant identifier C"ood practiceD. ;ay define na&e pace to "roup con tant . Cannot a%oid "lo(al7local na&e redefinition Ccan e%entually define na&e pace a cla e 0ith attri(ute acce control - not in Python pirit9 and e.ecution co tD. 3ee third party &odule pyenum for trict enu&-like na&e pace.
FLOW CONTROL
C"n-! !"n if cond : inst [ elif cond : inst ] [ else : inst ] L""p
for var[,] in iterable : inst [ else : inst ]
INTERPRETATION * EXECUTION
compile(string#,filename,kind$[,flags&[,dont_inherit&]]) code object eval(expression[,globals[,locals]]) value" evaluation4 of expression string eval(code_object[,globals[,locals]]) value" evaluation4 of code object exec5 statements [in globals[,locals]] statements string# executed4 execfile(filename[,globals[,locals]]) file interpreted'
,
OB+ECTS, NAMES
AND
NAMESPACES
I-en !.!e(s = e $ 'a-@4-LU)'a-@4-L0-EU)T 3pecial u a"e for under core $ _xxx "lo(al not i&ported (y import * _xxx i&ple&entation detail9 for internal u e C"ood practiceD __xxx Ppri%ateP cla &e&(er 9 defined a _ClassName__xxx __xxx__ nor&ally re er%ed (y Python Ca e i i"nificant $ This_Name SK THIS_NAME. O/0ec s 1n- N1&es, Re.e(ence C"un !n% <ata are typed o(8ect Call dataD9 na&e are dyna&ically (ound to o(8ect . = a i"n&ent tate&ent (ind re ult of ri"ht part e%aluation into left part na&eC D7containerC D. *.a&ple $ a = 3*c+5 a,b = ("Hello","World") x,y,tabz[i] = fct(i) s = "Hello" pi,e = 3.14,2.71 a,b = b,a
Fhen an o(8ect i no lon"er referenced C(y na&e or (y container D9 it i de troyed Cit __del__ ðod i then calledD. sys.getrefcount(object) int" current reference counter of object 3tandard &odule weakref define tool to allo0 o(8ect to (e "ar(a"e collected 0hen nece ary and dyna&ically re-created on-de&and.
while cond : inst 2here i no P 0itchP or Pca eP. [ else : inst ] Can u e if elif elif el e. Can u e a &appin" 0ith *.it loop 0ith break. function (ound to ca e . Io to ne.t iteration 0ith continue. Loop else (loc only e.ecuted 0hen loop e.it nor&ally C0ithout breakD.
Func !"ns*&e '"-s e2! *.it function7ðod 0ith return [value] *.it fro& "enerator (ody 0ith yield value ;ultiple returned %alue u in" tuple data. Cannot yield 0ithin a try7finally (lock. E2cep !"ns try : inst except [ except_class [,value ]] : inst [ else : inst ] Can ha%e a tuple of cla e for e.ceptUcla . :ot pecifyin" a cla catch all e.ception . 1lock else e.ecuted 0hen try (lock e.it nor&ally.
try : inst finally : inst Proce finally (lock in all e.ecution path Cnor&al or e.ceptionD. raise exception_class[,value[,traceback]] raise exception_object raise La t for& re-rai e the currently catched e.ception in an e.ception handler.
;ulti-line tate&ent in ource code &u t u e \n a ne0line9 and &u t (e ter&inated (y a ne0line. 2 /ind relati%e to trin" content9 'exec' e?uence of tate&ent 9 'eval' in"le e.pre ion9 'single' in"le interacti%e tate&ent. > -la" and dontUinherit are for future tate&ent C ee docD. 4 6n conte.t of "lo(al and local na&e pace . 5 *.ec i a lan"a"e tate&ent9 other are (uiltin function .
Mu 1/#e*I&&u 1/#e O/0ec s ;uta(le o(8ect can (e &odified in place. 6&&uta(le o(8ect cannot (e &odified C&u t (uild a ne0 o(8ect 0ith ne0 %alueD. Immutable $ bool9 int9 long9 float9 complex9 string9 unicode9 tuple9 frozenset9 buffer9 slice. Mutable $ list9 set9 dict and other hi"h le%el cla o(8ect . 2here i no con tant definition. Vu t u e upperca e na&e to identify y&(ol 0hich &u t not (e &odified. N1&esp1ces Place 0here Python found na&e . 1uiltin na&e pace na&e fro& &odule __builtins__9 already a%aila(le. Ilo(al na&e pace na&e defined at &odule le%el C@ero indentationD. Local na&e pace na&e defined in ðod 7function .
del name remove existing name from namespace (remove object binding) globals() dict" identifiervalue of global namespace locals() dict" identifiervalue of local namespace Current cope na&e directly u a(le. 3earched in local 9 then local 2a
P1(1&e e(s * Re u(n 31#ue Para&eter are pa ed (y reference to o(8ect . Jou can &odify %alue of &uta(le o(8ect type . Jou cannot &odify %alue of i&&uta(le o(8ect type - a if they 0ere pa ed (y %alue. :otation * %aria(le li t of anony&ou para&eter in a tuple. :otation ** %aria(le li t of na&ed para&eter in a dict. Return %alueC D 0ith return [value[,O]] -or &ultiple %alue 9 return a tuple. 6f no return %alue pecified or if end of function definition reached9 return None %alue. L1&/-1 .unc !"ns lambda param[,O] : expression 4nony&ou function defined inline. Re ult of expression e%aluation i returned Cit &u t (e an e.pre ion9 no loop9 no conditionD. *.pre ion u e %alue kno0n at definition ti&e Ce.cept for para& D. C1##1/#e O/0ec s #(8ect ha%in" a __call__ ðod can (e u ed a function . ;ethod (ound to o(8ect can (e u ed a function $ f = o.meth callable(x) bool" test x callable ith x() C1##!n% Func !"ns [name=] fctname((expr[,]][,name=expr[,][,*args][,**args]) 4nony&ou para&eter pa ed in para&eter order declaration. Para& ha%in" default %alue can (e o&itted. :otation * pa %aria(le li t of anony&ou para&eter in a tuple.
2c
I e(1/#e P(" "c"# Ieneric and i&ple protocol allo0in" to iterate on any collection of data. #(8ect of cla definin" __iter__ or __getitem__ are itera(le Cdirectly u a(le in for loop D. __iter__(self) iterator on self iter(object) iterator on iterable object iter(callable,sentinel) iterator returning callable() values up to sentinel
2b
:otation ** pa
Object Life __new__(classref,initargs) object of classref t!pe% alread! initiali/ed# __init__ Cself,initargs) called to initiali/e object ith initargs __del__ (self) called hen object ill be destro!ed , 6f donPt return a cla ref o(8ect9 then o(8ect.UUinitUU i called 0ith initar" . Object Cast __repr__(self) str" called for repr(self) and `self` __str__(selfD str" called for str(self) and print self __coerce__(self,other) value% called for coerce(self%other) Object Hash Key __hash__(self) int" hash code for object% used for hash(obj)and 0uick mapping ke!s comparison 1 default implementation use hash(id(self)) Attributes access 3ee al o Q<e criptor protocolQ infra. __getattr__(self,name) value% called for undefined attributes __getattribute__(self9 name) value% al a!s called __setattr__(self9 name, value) called for obj.name=value __delattr__(self9 name) called for del obj.name __hash__(self) int" &$ bits hash code% called for hash(obj) and dict
operations
Func !"ns C"n ("# sys.getrecursionlimit() int" current recursion limit for functions sys.setrecursionlimit(limit) set recursion limit for functions Dec"(1 "(s Ilue code Cfunction D called at function and ðod definition ti&e9 return the final function7ðod C"enerally 0ith 0rappin" codeD. @decoratorname [(decorator_argumentsD] 'O) def fct(fct_rguments):
@dec# @dec$(args) @dec& def fct(O):O def fct(O):O fct = dec#(dec$(args)(dec&(fct)))) 3ee pa"e PythonDecoratorLibrary in python.or" Fiki for o&e decorator definition .
like
-or copyin"9 o(8ect can define picklin" protocol too C ee -ile 3eriali@ation - p,2D9 in place of __copy__ and __deepcopy__.
In ("spec !"n 1eyond thi docu&entation. ;any __xxx___ attri(ute are defined9 o&e are 0rita(le C ee other doc D. 3ee tandard &odule inspect to &anipulate the e data.
"#ample of Introspection Attributes :ote$ cla e are o(8ect tooS __base__ list" parent classes of a class __slots__ tuple" allo ed objects attributes names# of a class __class__ class,type" object)s class __dict__ dict" defined attributes (object namespace) of an instance __doc__ string" documentation string of a package% module% class% function __name__ str" object definition name of a function __file__ string" pathname of loaded module 3p!c% 3p!o or 3p!d , Li t of allo0ed attri(ute na&e . = a"e di coura"ed.
TYPES*CLASSES ) OB+ECTS
4ll data are typed o(8ect relyin" to cla e . type(o) type" t!pe object of o 3tandard &odule types define type o(8ect for (uiltin type .
MODULES
AND
PACKAGES
C#1ss De.!n! !"n class classname [(parentclass[,O])] $ varname K expr varname defined in classname namespace def metname(self[,O]): define methods like functions 3upport &ultiple inheritance. Can inherit fro& (uiltin cla . 6nherit at lea t fro& object (a e cla K! Python Pne0 tyle cla P. -ir t para&eter of ðod i tar"et o(8ect9 tandard u e self na&e. 4cce cla &e&(er %ia cla na&e9 o(8ect &e&(er %ia self. 2hi doc con ider you u e ne0 tyle cla Cinheritin" fro& objectD.
Metaclass Cla definition create a ne0 type. 6t can (e done P(y handP 0ith $ x K type()classname)9(parentclass,[O]),{varname:expr[,O]} def metname(self[,O]): x.metname = metname 2hi allo0 creation of &etacla cla e Ccla (uildin" other cla D.
__call__(self9 *args, **kwargs) value% called for obj(O) Static metho / Class metho = e tandard decorator C ee <ecorator p>D. class Cla :a&e $ @staticmethod def &e '"-n1&e(): O @classmethod def methodname(classref,): O
O/0ec C(e1 !"n obj = *lass+ame(initargs) 6n ca of e.ception durin" initiali@ation9 o(8ect i de troyed 0hen e.itin" init code Creference counter reach @eroD. C#1sses ) O/0ec s Re#1 !"ns isinstance(obj,classinfo) bool" test object of t!pe,class classinfo issubclass(aclass, aparent) bool" test same class or parent relationship Prefer i in tanceCD to typeCD for type checkin".
Parent cla ðod are not auto&atically called if o%erriden in u(cla - they &u t (e e.plicitly called if nece ary. Call parent ðod %ia super function $ super(-his*lass,self).methodname(self,args) #r the old 0ay9 %ia parent cla na&e pace $ .arent*lass.methodname(self,args)
Desc(!p "(s p(" "c"# <e criptor are attri(ute o(8ect controlin" acce to attri(ute %alue . 2hey &u t define o&e of follo0in" ðod $ __get__(self,obj,ownerclass) attribute value for obj __set__(self,obj,value) modif! attribute in obj% set to value __delete__(self,obj) remove attribute from obj 6n the e ðod self i the de criptor o(8ect9 and obj i the tar"et o(8ect 0hich attri(ute i &anipulated.
!roperties A descriptor to directly bind methods/functions to control attribute access. Use builtin type property with init args. class 2!*lass : attributename = property(getter,setter,deleter,description) *ach init ar" default to :one Cie. undefinedD.
-ile gabuzo.py &odule gabuzo. <irectory kramed/ 0ith a file __init__.py packa"e kramed. Can ha%e u(-packa"e C u(directorie ha%in" __init__.py fileD. 3earched in the Python PATH. Current Python P42G tored in sys.path li t. Contain directorie and .@ip file path . 1uilt fro& location of tandard Python &odule 9 PJ2G#:P42G en%iron&ent %aria(le9 directory of &ain &odule "i%en on co&&and line9 data pecified in line of $pth file found in Python ho&e directory9 and data pecified in re"i try under Findo0 . Current li t of loaded &odule tored in sys.modules &ap C&ain &odule i under key __main__D. import module [as alias] [,] from module import name [as alias] [,] from module import * reload(module) module is reloaded (but old references still on old module
content)
6&port can u e packa"e path Ce.$from encoding.aliases importD. <irect i&port fro& a packa"e u e definition fro& __init__.py file. +ery careful 0ith import * a i&ported na&e o%erride na&e already defined. 2o li&it your &odule na&e e.ported and %i i(le (y import *9 define &odule "lo(al __all__ 0ith li t of e.ported na&e Cor u e "lo(al na&e _xxxD. 3ee __import__ (uiltin function9 imp (uiltin &odule and ihooks &odule. __import__(modulename[9 globals[9locals[9lnameslist]]])
setattr(object,name,value) object attribute set to value object.name value of object attribute getattr(object,name[9default]) value of object attribute del object.name delattr(object,name) object attribute removed
C"py!n% O/0ec s 4 i"n&ent only duplicate reference . 2o hallo0 copy an o(8ect C(uild a ne0 one 0ith a&e %alue - referencin" a&e contentD9 or to deep copy an o(8ect Cdeep-copyin" referenced contentD9 ee o(8ect copy ðod 9 and function in tandard &odule copy. copy.copy(object) value" shallo cop! of object copy.deepcopy(object[[,memo],_nil]) value" deep cop! of object# , Para& memo and nil are u ed in recur i%e deepcopy9 their default %alue are None and e&pty li t.
Copy !rotocol __copy__(self) value" shallo cop! of self% called b! copy.copy() __deepcopy__(self,memo) value" deep cop! of self% called b! copy.deepcopy() 3b
S"u(ce enc"-!n%s 3ee P*P 26>. <eclare ource file encodin" in fir t or econd line in a pecial co&&ent. # -*- coding: encoding_name -*6f thi i not pecified9 Python u e sys.getdefaultencoding() %alue C ee &odule sitecustomize.py and user.pyD. 6t i i&portant to pecify encodin" of your &odule a uQQ trin" u e it to correctly (uild unicode literal . Spec!1# A (!/u es __name__ str" module name% )__main__' for command1line called script __file__ string" pathname of compiled module loaded
Spec!1# Me '"-s #ther pecial o%errida(le UU...UUU ðod are li ted in re pecti%e ection .
3a
4t end of &odule9 0e &ay ha%e $ if __name__=='__main__' : # main code # generally call a 'main' function: mainfunction(sys.argv[1:]) # or in lib modules, execute test/demo code... *.ecution e.it after la t &ain &odule in truction Cin &ultithread9 0ait al o for end of non-dae&on thread D9 unle interacti%e &ode i forced. Can force e.it 0ith callin" sys.exit(code)9 0hich rai e a SystemExit e.ception - ee Current Proce - *.itin" Cp,>D.
Comparison O%erri in& __lt__(self, __le__(self, __gt__(self, __ge__(self, __eq__(self, __ne__(self, other) bool# " called for self < other other) bool# " called for self <= other other) bool# " called for self > other other) bool# " called for self >= other otherD bool# " called for self == other other) bool# " called for self != other and for self <> other __cmp__(self,other) int " called for self compared to other% self<othervalue<4% self55othervalue54% self>othervalue>4 , 4ny %alue u a(le a (oolean %alue9 or a NotImplemented %alue if cannot co&pare 0ith uch other type.
BOOLEANS
-al e $ None9 @ero nu&(er 9 e&pty container . False 0. 2rue $ if not fal e. True 1. bool(expr) True W False Lo"ical not $ not expr Lo"ical and $ expr# and expr$ Lo"ical or $ expr# or expr$ Lo"ical and and or u e hort path e%aluation. 'ool Cast O%erri in& __nonzero__(self) bool " test object itself# , 6f UUnon@eroUU undefined9 look at UUlenUU9 el e o(8ect i true.
OPERATORS
<eal 0ith arith&etic9 (oolean lo"ic9 (it le%el9 inde.in" and licin".
P(!"(! y
, (a,) [a,] 6 x+! x-! A x<<! x>>! B x&! E x^! ,0 x|! ,, x<! x<=! x>! x>=! x==! x!=! x<>! x is ! x is not ! x in s x not in s ,2 not x ,> x and ! ,4 x or ! ,5 lambda args:expr
{a:b9} ``
2 s[i] s[i:j] s.attr f() > +x -x ~x 4 x**! 5 x*! x/! x%!
Ope(1 "(s 1s Func !"ns #perator are al o defined a function in tandard operator &odule.
Comparison lt(a,b) K __lt__(a,b) le(a,b) K __le__(a,b) eq(a,b) K __eq__(a,b) Lo&ical / 'oolean not_(o) K __not__(o) truth(o) is_(a,b) is_not(a,b) Arithmetic abs(o) K __abs__(o) add(a,b) K __add__(a,b) sub(a,b) K __sub__(a,b) mul(a,b) K __mul__(a,b) div(a,b) K __div__(a,b) mod(a,b) K __mod__(a,b) 'it Le%el lshift(a,b) K __lshift__(a,b) rshift(a,b) K __rshift__(a,b) inv(o) K invert(o) K __inv__(o) K __invert__(o) Se(uences concat(a,b) K __concat__(a,b) contains(a,b) K __contains__(a,b) countOf(a,b) indexOf(a,b) repeat(a,b) K __repeat__(a,b) setitem(a,b,c) K __setitem__(a,b,c) getitem(a,b) K __getitem__(a,b) delitem(a,b) K __delitem__(a,b) setslice(a,b,c,v) K __setslice__(a,b,c,v) getslice(a,b,c) K __getslice__(a,b,c) delslice(a,b,c) K __delslice__(a,b,c) )ype )estin& 2he e function &u t (e con idered a not relia(le. isMappingType(o) isNumberType(o) isSequenceType(o) Attribute an Item Loo*up attrgetter(attr) fct" here fct(x)x3attr itemgetter(item) fct" here fct(x)x(item6 4b truediv(a,b) K __truediv__(a,b) floordiv(a,b) K __floordiv__(a,b) neg(o) K __neg__(o) pos(o) K __pos__(o) pow(a,b) K __pow__(a,b) and_(a,b) K __and__(a,b) or_(a,b) K __or__(a,b) xor(a,b) K __xor__(a,b) ne(a,b) K __ne__(a,b) ge(a,b) K __ge__(a,b) gt(a,b) K __gt__(a,b)
NUMBERS
1uiltin inte"er type $ int Clike C lon"D9 long Cunli&ited inte"erD int(expr[,base5#4]) int" cast of expr long(expr[,base5#4]) long" cast of expr 1uiltin floatin" point type $ float Clike C dou(leD9 complex Creal and i&a"inary part are floatD. float(expr) float" representation of expr complex(x[9!]D complex" number" x7!j [xX]!j complex" number% ex" &7'j 183$j c.real float" real part of complex number c.img float" imaginar! part of complex number c.conjugate() complex" conjugate of complex number (real%1img) ;a.i&u& int inte"er in y .&a.int. 4uto&atic con%er ion (et0een nu&eric type . 4uto&atic con%er ion fro& int to lon" 0hen re ult o%erflo0 &a. int. <irect con%er ion fro&7to trin" fro&7to int9 lon" %ia type con tructor . 2ype Decimal defined in tandard &odule decimal. 1a e fi.ed type co&pact tora"e array in tandard &odule array.
A(! '&e !c Ope(1 "(s Can (e defined for any data type.
Arithmetic O%erri in& __add__(self,other) value" called for self + other __sub__(self,other) value" called for self - other __mul__(self,other) value" called for self * other __div__(self,other) value" called# for self / other __truediv__(self,other) value" called$ for self / other __floordiv__(self,other) value" called for self // other __mod__(self,other) value" called for self % other __divmod__(self,other) value" called for divmod(self,other) __pow__(self,other) value" called for self ** other __nonzero__(self) value" called for nonzero(self) __neg__(self) value" called for -self __pos__(self) value" called for +self __abs__(self) value" called for abs(self) __iadd__(self,other) called for self += other __isub__(self,other) called for self -= other __imul__(self,other) called for self *= other __idiv__(self,other) called# for self /= other __itruediv__(self,other) called$ for self /= other __ifloordiv__(self9 other) called for self //= other __imod__(self,other) called for self %= other __ipow__(self,other) called for self **= other , 0ithout 7 2 0ith fro& UUfuturUU i&port di%i ion 1inary operator __xxx__ ha%e al o __rxxx__ for& 9 called 0hen tar"et o(8ect i on ri"ht ide.
Ope(1 "(s -x +x x+! x-! x*! x/! , x//! , x%! 2 x**! 2 , Fith from __future__ import di%i ion9 / i true di%i ion C1/20.5), and // is floor division 1//20). !lse for integers / is still floor division. " % is remainder operator, ** is power elevation operator same as pow). Func !"ns #ome functions in builtins. abs(x) absolute value of x divmod(x,!) (x,!,x9!) oct(integer) str" octal representation of integer number hex(integer) str" hexadecimal representation of integer number
Math +unctions #tandard floating point functions/data in standard math module. acos(x) float" radians angle for x cosinus value " (1##6 (4:6 asin(x) float" radians angle for x sinus value " (1##6 (1:,$7:,$6 atan(x) float" radians angle for x tangent value " (1;;6 61:,$7:,$( atan2(x,!) float" randians angle for x,! tangent value ceil(x) float" smallest integral value >5 x cos(x) float" cosinus value for radians angle x cosh(x) float" h!perbolic cosinus value for radians angle x exp(x) float" exponential of x 5 ex fabs(x) float" absolute value of x floor(x) float" largest integral value <5 x fmod(x,!) float" modulo 5 remainder of x,! frexp(x) (float,int)4 (m%!) m mantissa of x,! exponent of x here ldepx(x,i) x < ($<<i) 4c
.K&T2y
C"&p1(!s"n Ope(1 "(s #perator can co&pare any data type . Co&pare values 0ith < <= > >= == != <>. 2e t o(8ect identity 0ith is and is not Cco&pare on id(obj)D. <irect co&po ition of co¶tor i allo0ed in e.pre ion $ x<!<=/>t. 1uiltin function cmp(o#,o$) -1 Co# < o$D9 0 Co# KK o$D9 1 Co# ! o$D
4a
log(x) float" neperian logarithm of x log10(x) float" decimal logarithm of x modf(x) (float{$}): (f%i) f signed fractional part% i signed integer part pow(x,!) float" x raised to ! po er sin(x) float" sinus value for radians angle x sinh(x) float" h!perbolic sinus value for radians angle x sqrt(x) float" s0uare root of x (x) tan(x) float" tangent value for radians angle x tanh(x) float" h!perbolic tangent value for radians angle x pi float" value of (pi53.1415926535897931) e float" value of neperian logarithms base (e52.7182818284590451) ;odule cmath pro%ide i&ilar function for complex nu&(er . ,an om -umbers Rando&i@ation function in tandard random &odule. ;odule function u e an hidden9 hared tate9 Random type "enerator Cunifor& di tri(utionD. -unction al o a%aila(le a ðod of Random o(8ect . seed([.]) initiali/e random number generator random() float" random value in (434% #34( randint(a9b) int" random value in (a% b6 uniform(a9 b) float" random value in (a% b( getrandbits(k) long" ith k random bits randrange([start,]stop[,step]) int" random value in range(start, stop, step) choice(se0) value" random item from se0uence shuffle(x[,rndfct]) items of x randoml! reordered using rndfct() sample(population9k) list" k random items from polulation 4lternate rando& di tri(ution $ betavariate(alpha,beta)9 expovariate(lambd)9 gammavariate(alpha9beta)9 gauss(mu,sigma)9 lognormvariate(mu, sigma)9 normalvariate(mu,sigma)9 vonmisesvariate(mu,kappa)9 paretovariate(alpha)9 weibullvariate(alpha,beta). 4lternate rando& "enerator WichmannHill cla . <irect "enerator &anipulation $ getstate()9 setstate(state)9 jumpahead(n). 6n &odule os9 ee $ os.urandom(n) str" n random b!tes suitable for cr!ptographic use Other Math Mo ules 4d%anced &atri.9 al"orith& and nu&(er crunchin" in third party &odule like numarray 7 Numeric Ckno0n a :u&PyD9 gmpy C&ultipreci ion arith&eticD9 DecInt9 scipy9 3ee ite SciPy9 BioPython9 PyScience9 -umbers Casts O%erri in& __int__(self) int" called for intCselfD __long__(self) long" called for long(self) __float__(self) float" called for float(self) __complex__(self) complex" called for complex(self) __oct__(self) str" called for oct(self) __hex__(self) str" called for hex(self) __coerce__(self,other) value" called for coerce(self,other)
x&! bit ise and on x and ! x|! bit ise or on x and ! x<<n x shifted left b! n bits (/eroes inserted) x>>n x shifted right b! n bits (/eroes inserted)
unicode(object[,encoding[,errors]]) unicode" unicode sys.maxunicode int" maximum unicode code5fct(compile time option) .nico e Chars Informations ;odule unicodedata contain infor&ation a(out =nicode char propertie 9 na&e . lookup(name) unicode char from its name name(unichr[,default]) str" unicode name 1 ma! raise ValueError decimal(unichr[,default]) int" decimal value 1 ma! raise ValueError digit(unichr[,default]) int" digit value 1 ma! raise ValueError numeric(unichr[,default]) float" numeric value 1 ma! raise ValueError category(unichr) str" general unicode categor! of char bidirectional(unichr) str" bidir categor! of char% ma! be empt! str combining(unichr) str,0" canonical combining class of char as integer east_asian_width(unichr) str" east asian idth mirrored(unichr) int" mirrored propert! in bidi text% # if mirrored else 4 decomposition(unichr) str" decomposition mapping% ma! be empt! str normalizeCform, unistr) str" normal form of string 1 form in 'NFC'% )NFKC'% 'NFD'% 'NFKD' unidata_version str" version of =nicode database used
1inary tructure &anipulation in tandard &odule struct. 4d%anced (inary tructure &appin" and &anipulation in third party &odule $ ctypes9 xstruct9 'it Le%el O%erri in& __and__(self,other) value" for self & other __or__(self,other) value" for self | other __xor__(self,other) value" for self ^ other __lshift__(self,other) value" for self << other __rshift__(self,other) value" for self >> other __invert__(self) value" for ~self __iand__(self,other) called for self &= other __ior__(self,other) called for self |= other __ixor__(self,other) called for self ^= other __ilshift__(self,other) called for self <<= other __irshift__(self,other) called for self >>= other
STRINGS
3i&ple ?uoted 'Hello' or dou(le-?uoted "Hello". = e triple ' i&pleWdou(le) ?uote for &ulti-line trin" $ """Hello, how are you ?""" 3trin" are i&&uta(le Conce created a trin" cannot (e &odified in placeD. 3trin" can contain (inary data9 includin" null char Cchar of code 0D. 3trin" are e?uence 9 ee 6nde.in" CpBD for char inde.ation C licin"D and other operation . chr(code) char ord(char) code str(expr) readable textual representation of expr 1 if available `expr` readable textual representation of expr 1 if available repr(expr) evaluable textual representation of expr 1 if available \a \b \e \f \n \r \t -
Esc1pe se5uences (ell (ack pace e cape for& feed ne0 line carria"e return hori@ontal ta(
\v - %ertical ta( \' - in"le ?uote \" - dou(le ?uote \\ - (ack la h \ooo - char (y octal ooo %alue \xhh - char (y he.adeci&al hh %alue \<ne line> - continue trin" on ne.t line.
4nd for =nicode trin" $ \uxxxx - unicode char (y ,6 (it he.adeci&al xxxx %alue. \Uxxxxxxxx - unicode char (y >2 (it he.adeci&al xxxxxxxx %alue. \N{name} - unicode char (y na&e in the =nicode data(a e. /eep \ e cape char (y prefi.in" trin" literal 0ith a r Cor RD - for Pra0P trin" Cnote $ cannot ter&inate a ra0 trin" 0ith a \D.
Un!c"-e s (!n%s Quoted a for str9 (ut 0ith a u Cor UD prefi. (efore the trin" $ u"Voii" U"""Une bonne journe en perspective.""" Can &i. trin" prefi. r Cor RD and u Cor UD. Jou &u t define your ource file encodin" o that Python kno0 ho0 to con%ert your ource literal trin" into internal unicode trin" . unichr(code) unicode" string of one unicode char ord(unicode char) int" unicode code
5b
Me '"-s 1n- Func !"ns -ro& (uiltin C ee al o oct and hex function for inte"er to trin" D $ len(s) int" number of chars in the string ;o t trin" ðod are al o a%aila(le a function in the tandard string &odule. s.capitalize() string ith first char capitali/ed# s.center( idth[,fillchar]) string centered s.count(sub[,start[,end]]) int" count sub occurences ithin start1end s.decode(6encoding[,errors]]) unicode" text decoded 1 see encodings s.encode(6encoding[,errors]]) str" ext encoded 1 see encodings s.endswith(suffix[,start[,end]]) bool s.expandtabs([tabsi/e]) string ith tabs replaced b! spaces s.find(sub[,start[,end]]) int,-1" offset of sub ithin start1end s.index(sub[,start[,end]]) int" offset of sub 1 ma! raise ValueError s.isalnum() bool" non empt! string ith all alphanumeric chars# s.isalpha() bool" non empt! string ith all alphabetic chars# s.isdigit() bool" non empt! string ith all digit chars# s.islower() bool" non empt! string ith all lo er chars# s.isspace() bool" non empt! string ith all space chars# s.istitle() bool" non empt! string ith titlecase ords# s.isupper() bool" non empt! string ith all upper chars# s.join(se0) string" se0(467s7se0(#67s77se0(n1#6 s.ljust( idth[,fillchar]) text string left aligned$ s.lower() text string lo ered# s.lstrip(6chars]) string text ith leading chars$ removed s.replace(old,ne [,count]) string ith count firsts old replaced b! ne s.rfind(sub[,start[,end]]) int,-1" last offset of sub ithin start1end s.rindex(sub[,start[end]]) int" last offset of sub 1 ma! raise ValueError s.rjust( idth[,fillchar]) string text right aligned$ s.rsplit([sep[,maxsplit]]) [string]" rightmost ords delim3 b! sep$ s.rstrip(6chars]) string ith trailing chars$ removed s.split([sep[,maxsplit]]) [string]" ords delimited b! sep$ s.splitlines([keepends]) [string]" lines s.startswith(suffix[,start[,end]]) bool s.strip(6chars]) string text ith leading7trailing chars$ removed s.swapcase() string ith case s itched# s.title() string ith ords capitali/ed#
5c
s.translate(table[,deletechars]) string" cleaned% converted& s.upper() string uppered# s.zfill( itdh) string" numeric string
, 2
3ee al o e.ternal pro8ect pyparsing9 PLJ CPython Le.-JaccD9 tpg C2oy Par er IeneratorDO "#pressions ;etacharacter $ . ^ $ * + ? { } [ ] \ | ( )9 &ay u e \ e cape. . &atch any character e.cept a ne0line Cincludin" ne0line 0ith DOTALL optionD ^ &atch tart of trin" Cand tart of line 0ith MULTILINE optionD $ &atch end of trin" Cand end of line 0ith MULTILINE optionD expr* &atch 0 or &ore repetition of expr Ca &uch a po i(leD expr+ &atch , or &ore repetition of expr Ca &uch a po i(leD expr? &atch 0 or , e.pr expr*? &atch like expr* (ut a fe0 a po i(le expr+? &atch like expr+ (ut a fe0 a po i(le expr?? &atch like expr? (ut a fe0 a po i(le expr{m} &atch m repetition of expr expr{[m],[n]} &atch fro& m to n repetition of expr9 &i in" m default to 0 and &i in" n default to infinite expr{[m],[n]}? &atch like expr{[m],[n]} (ut a fe0 a po i(le [set] &atch one char in the set defined (y $ ^ at (e"inin"9 in%ert et definition x-! char fro& x to ! \x ee * cape e?uence for trin" Cp5D \- 9 \] char - and ] C- and ] at the (e"innin" &atch - and ] char D x char x Cincludin" other re &etacharacter D expr>|exprC &atch expr> or exprC9 hort path e%aluation (expr) &atch expr and (uild a nu&(ered "roup (?[i][L][m][s][u][x]) Cat lea t one ot iLmsux charD "roup &atch e&pty trin"9 &odify option fla" for entire e.pre ion - ee I L M S U X option (?:expr) &atch expr (ut dont (uild a "roup (?P<name>expr) &atch expr and (uild a "roup nu&(ered and na&ed Cname &u t (e %alid Python identifierD (?P=name) &atch te.t &atched (y earlier "roup na&ed name (?#text) no &atch9 text i 8u t a co&&ent (?=expr) &atch if &atch expr (ut donPt con u&e input (?!expr) &atch if doe nPt &atch expr (ut donPt con u&e input (?<=expr) &atch if current po ition i i&&ediatly preceded (y a &atch for fi.ed len"th pattern expr (?<!expr) &atch if current po ition i i&&ediatly not preceded (y a &atch for fi.ed len"th pattern expr (?(num,name)!esexpr[|noexpr]) try to &atch !esexpr if "roup num,name e.i t 9 el e try to &atch noexpr "scape Se(uences \n \nn &atch> "roup nu&(er n CnnD 0here fir t n0 \ooo \0o &atch> char 0ith octal %alue ooo C0oD \A &atch only at the tart of the trin" \b &atch> e&pty trin" at (e"innin" or end of a 0ord,X2 \B &atch e&pty trin" not at (e"innin" or end of a 0ord,X2 \d &atch char cla deci&al di"it [0-9] \D &atch char cla non-di"it [^0-9] \s &atch char cla 0hite pace [ \t\n\r\f\v] \S &atch char cla non-0hite pace [^ \t\n\r\f\v] \w &atch char cla alphanu&eric [a-zA-Z0-9_] \W &atch char cla non-alphanu&eric [^a-zA-Z0-9_] \Z &atch end of trin" \a \b \f \n \r \t \v \x \\ a&e a trin" e cape \c for other c char , match char c
, 2 >
+la& Options IGNORECASE CID $ ca e in en iti%e e.pre ion - not locale dependant. LOCALE CLD $ &ake \w \W \b \B locale dependant. MULTILINE CMD $ ^ and $ &atch (e"inin"7end of trin" and line . *l e ^ and $ &atch only (e"innin" and end of trin". DOTALL CSD $ &ake . &atch any char includin" ne0line. *l e ne0line e.cluded. UNICODE CUD $ &ake \w \W \b \B unicode dependant. VERBOSE CXD $ i"nore 0hite pace and &ake # tartin" co&&ent Ce.cept 0hen pace and # are e caped or in char cla D. Matchin& an Searchin& Can u e re function 9 or co&pile e.pre ion into SRE_Pattern o(8ect and u e their ðod . 3ee -la" #ption upra for flags para&eter . search(pattern,string[,flags]) MatchObject,None" scan throught string to match(pattern,string[,flags]) MatchObject,None" tr! to match string
find substring matching pattern ith pattern split(pattern,string[,maxsplit54]) [string]" split string b! occurences of pattern 1 if maxsplit specified% remainder is put in last item of list findall(pattern,string[,flags]) [string],[(string)]" find non1overlapping substrings matching pattern 1 eventuall! empt! matchs 1 return list of tuples if pattern has groups finditer(pattern,string[,flags]) iterator over [MatchObject] 1 same as findall but ith an iterator sub(pattern,repl,string[,count54]) string" replace substrings matching pattern b! repl 1 repl as string can contain back references# to identified substring 1 repl as fct(2atchDbject) return replacement string 1 pattern ma! be RE_Pattern object
Locale dependant for B (it trin" . <efault char 7 eparator7fillchar i pace. > -or tr ta(le &u t (e a trin" of 256 char - ee string.maketrans(). -or =nicode no deletechar 9 and ta(le &u t (e a &ap of unicode ordinal to unicode ordinal .
F"(&1 !n% = e % operator (et0een for&at trin" and ar"u&ent $ string%args -or&atin" string contain %[(name)][flag][ idth][.precision]code 6f not u e %(name)O args K in"le %alue or tuple of %alue . 6f u e %(name)O args $ mapping with name as %eys. -or &appin"9 args can (e an o(8ect 0ith __getitem__ ðod - ee #%erridin" ;appin" #peration CpBD.
+ormat char co es d o x e f g c r i"ned int. deci&al $ &324 un i"ned octal $ 774 un i"ned he.a $ f3a float. point e.p. $ -3.256e-12 float. point dec. $ -0.0000032 li%e e or f character C, char tr or codeD o(8ect for&at like repr(object) )emplates Fith string.Template o(8ect . = e co&&on Y ynta. $ $$single ' ( $name or ${name} value for name. tmpl = string.Template(template_string) tmpl.substitute(mapping[,**k args]D string" template filled tmpl.safe_substitute(mapping[,**k args]) string" template filled tmpl.template string Can u(cla 2e&plate to (uild your o0n te&platin" C ee doc9 ource D. 3ee al o &odule formatter9 textwrap. i u X E F G % s i"ned int. deci&al $ &324 un i"ned deci&al 6953 un i"ned he.a $ F3A float. point e.p. $ -3.256E-12 float. point dec. $ -0.0000032 like E or F %% % o(8ect for&at like str(object)
subn(pattern,repl,string[,count54]) (string,int)" same as sub% $nd item is escape(string) string" non1alphanumerics backslashed 6f you need to reu e a pattern9 co&pile it one ti&e for all. pat = re.compile(pattern[,flags]) RE_Pattern object pat.match(string[,pos[9endpos]]) same as match function$ pat.search(string[,pos[9endpos]]) same as search function$ pat.split(string[,maxsplit54]) same as split function$ pat.findall(string[,pos[,endpos]]) same as findall function$ pat.finditer(string[,pos[,endpos]]) same as finditer function$ pat.sub(repl,string[,count54]) same as sub function pat.subn(pattern,repl,string[,count54]) same as subn function pat.flags int" flags used at compile time pat.pattern string" pattern used at compile time pat.groupindex dict" mapping of group names to group numbers 3e%eral function 7ðod return MatchObject o(8ect . m.expand(template) string" do backslash substitution on template (like sub
method) using match object groups values m.group([group[,]]) string,(string)" subgroups of the match from numbers or names m.groups([default5+one]) (string)" all subgroups of the match 1 default give access to subgroups not in the match m.groupdict([default5+one]) dict" namesubgroup" all named subgroups of the match 1 default give access to subgroups not in the match m.start([group54]) int" index of start of substring matched b! group% 1# if group exist but not in match m.end([group54]) int" index of end of substring matched b! group% -1 if group exist but not in match m.span([group54]) (int{$})" values of start and end methods for the group> m.pos int" pos value of search,match method m.endpos int" endpos value of search,match method count of substitutions
C"ns 1n s 3tandard &odule string pro%ide e%eral con tant Cdo not &odify9 they are u ed in trin" &anipulation function D and o&e tr function are not a%aila(le a ðod . ascii_letters str" lo ercase and uppercase chars ascii_lowercase str" lo ercase a1/ chars ascii_uppercase str" uppercase >1? chars digits str" 41@ decimal digit chars hexdigits str" 41@a1f>1A hexadecimal digit chars letters str" lo ercase and uppercase chars# lowercase str" lo ercase a1/ chars# octdigits str" 41B octal digit chars punctuation str" ascii chars considered as punctuation in * locale printable str" printable chars uppercase str" uppercase >1? chars# whitespace str" hitespace chars (spc% tab% cr% lf% ff% vt) capwords(s) str" split capitali/e join maketrans(from,to) translation table usable in str3translate 1 from and to
must have same length
1
Re%u#1( E2p(ess!"ns 3tandard &odule re ha a po0erfull re"e.p en"ine. 3ee re"e.p G#F2# at http://www.amk.ca/python/howto/regex/. = e ra0 trin" r"" notation.
6a
<epend on =:6C#<* fla". <epend on L#C4L* fla". Fhen out of char cla definition C[]D
6b
6c
m.lastindex int,None" index of last matched capturing group m.lastgroup string,None" name of last matched capturng group m.re RE_Pattern" pattern used to produce match object m.string string" string used in match,search to produce match object
, ,
key
1ack reference e.tended to \g<groupnum> and \g<groupname>. = in" part of trin" (et0een pos and endpos. Iroup nu&(er 0 corre pond to entire &atchin".
L"c1#!71 !"n 3tandard &odule locale pro%ide po i. locale er%ice Cinternationali@ationD. setlocale(categor![,locale]) current,ne settings" if locale specified
(string or tuple(language code% encoding)% modif! locale settings for categor! and return ne one 1 if locale not specified or None% return current locale 1 not thread safe localeconv() dict" database of local conventions
MON_1O MON_12 ABMON_1O ABMON_12 RADIXCHAR THOUSEP YESEXPR NOEXPR CRNCYSTR ERA ERA_YEAR ERA_D_T_FMT ERA_D_FMT ALT_DIGITS
key
nl_langinfo( value usage name of the nth month abbreviated name of the n month
th
'ase A!I bindtextdomain(domain[,localedir]) str" bounded director! 1 bind domain bind_textdomain_codeset(domain[,codeset]) codeset binding" bind
to localedir director! if specified (used hen searching for 3mo files) domain to codeset if specified 1 change xxgettext() returned strings encoding
radix character (decimal dot,comma,) separator character for thousands regular expression (of * librar!G) usable for !es repl! regular expression (of * librar!G) usable for no repl! currenc! s!mbol% preceded b! - if should appear before the value% b! + if should appear after the value% b! . if should replace radix character era 1 generall! not defined 1 same as E format in
textdomain([domain]) global domain" set global domain if specified and not None gettext(message) string" locali/ed translation of message 1 based on current global domain% language% and locale director! 1 usuall! aliased as _ in
local namespace
lgettext(message) string" like gettext()% using preferred encoding dgettext(domain,message) string" like gettext()% looking in specified ldgettext(domain,message) string" like dgettext()% using preferred
encoding domain3
strftime()
!ear in era usable as format for strftime() for date and time usable as format for strftime() for date up to #44 values representing 4 to @@ ith era ith era
ngettext(singular,plural,n) string" like gettext()% but consider plural lngettext(singular,plural,n) string" like ngettext()% using preferred
encoding forms (see .!thon and H+= gettext docs)
localecon% *eys
meaning
dngettext(domain,singular,plural,n) string" like ngettext()% looking in Local currency y&(ol for moneta!y %alue . <eci&al point character for numbe!s. :u&(er of fractional di"it u ed in local for&attin" of moneta!y %alue . [int]$ relati%e po ition of Pthou and U epP in numbe!s. CHAR_MAX at the end top "roupin". 0 at the end repeat la t "roup. 6nternational currency y&(ol of moneta!y %alue . :u&(er of fractional di"it u ed in international for&attin" of moneta!y %alue . <eci&al point u ed for moneta!y %alue . *?ui%alent to P"roupin"P9 u ed for moneta!y %alue . Iroup eparator u ed for moneta!y %alue . 2rue if currency y&(ol preceed ne"ati%e moneta!y %alue 9 fal e if it follo0. 2rue if there i a pace (et0een currency y&(ol and ne"ati%e moneta!y %alue. Po ition of ne"ati%e i"n for moneta!y %alue ,. 3y&(ol u ed to annotate a ne"ati%e moneta!y %alue. 2rue if currency y&(ol preceed po iti%e moneta!y %alue 9 fal e if it follo0. 2rue if there i a pace (et0een currency y&(ol and po iti%e moneta!y %alue. Po ition of po iti%e i"n for moneta!y %alue ,. 3y&(ol u ed to annotate a po iti%e moneta!y %alue. Character u ed (et0een "roup of di"it in numbe!s. ldngettext(domain,singular,plural,n) string" like dngettext()% using
preferred encoding specified domain3
getpreferredencoding([do_setlocale]) str" user preffered encoding for text data 1 set do_setlocale to False to avoid possible call to setlocale() normalize(localename) normali/ed locale code for localename 1 usable ith setlocale() 1 return localename if normali/ation fails resetlocale([categor!]) reset locale for categor! to default setting 1 categor! default to LC_ALL strcoll(s#9s$) int" compare t o strings 1 follo E*_*DEE>-F setting 1
return 4 if s#55s$% <4 if s#<s$% >4 if s#>s$ strxfrm(string) string"transform string for locale1a are comparison
Ienerally _ i (ound to gettext.gettext9 and tran lata(le trin" are 0ritten in ource u in" _('thestring'). 3ee doc for u a"e e.a&ple . Class base A!I 2he reco&&ended 0ay. ;odule gettext define a cla Translations9 dealin" 0ith .&o tran lation file and upportin" str7unicode trin" . find(domain[,localedir[,languages[,all]]]) str,None" 3mo file name for
translations (search in localedir,language,E*_2FII>HFI,domain3mo)
int_curr_symbol int_frac_digits mon_decimal_point mon_grouping mon_thousands_sep n_cs_precedes n_sep_by_space n_sign_posn negative_sign p_cs_precedes p_sep_by_space p_sign_posn positive_sign thousands_sep
,
formatCformat,val[,grouping]) string"convert val float using format (9 operator conventions) 1 follo LC_NUMERIC settings (decimal point% 7
grouping if it is true) str(float) string" convert float 1 follo LC_NUMERIC settings (decimal point) atof(string) float" convert string to float 1 follo LC_NUMERIC settings
atoi(string) int" convert string to integer 1 follo LC_NUMERIC settings CHAR_MAX s!mbolic constant used b! localeconv() Cate&ories LC_CTYPE character t!pe 1 case change behaviour LC_COLLATE strings sorting 1 strcoll() and strxfrm() functions LC_TIME time formating 1 time.strftime() LC_MONETARY monetar! values formating 1 options from localeconv() LC_MESSAGES messages displa! 1 os.strerror() 1 not for .!thon LC_NUMERIC numbers formatting 1 format()% atoi()% atof() and str()
of this module (dont modif! normal .!thon number formating) LC_ALL all locales 1 used to change,retrieve the locale for all categories messages
-ull )ranslations 2he NullTranslations i a (a e cla for all 2ran lation . t.__init__([fp]) initiali/e translations" fp is a file object 1 call _parse(fp) if
it is not +one
t._parse(fp) nothing" subclasses override to read data from the file t.add_fallback(fallback) add fallback used if cannot found translation <efine ðod gettext9 lgettext9 ngettext9 lngettext a in the (a e 4P6. 4nd define peciale ðod ugettext and ungettext returnin" unicode trin" Cother for& return encoded str trin" D. Return tran lated &e a"e9 for0ardin" to fall(ack if it i defined. #%erriden in u(cla e . t.info() return protected _info attribute t.charset() return protected _charset attribute t.output_charset() return protected _output_charset attribute t.set_output_charset(charset) set _output_charset attribute t.install([unicode]) bind _ in builtin namespace to self3gettext() or self3ugettext() upon unicode (default to false) G-. )ranslations 2he GNUTranslations cla C u(cla of NullTranslationsD i (a ed on I:= "ette.t and .&o file . ;e a"e id and te.t are coerced to unicode. Protected _info attri(ute contain &e a"e tran lation . 7c
(defining encoding used to return translated messages) for a message
nl/lan&info options
key
nl_langinfo( value usage name of character encoding usable as format for strftime() for time and date usable as format for strftime() for date usable as format for strftime() for time usable as format for strftime() for time in am,pm format name of the nth da! of the eek 1 first da! is sunda! eek 1 first da! is abbreviated name of the nth da! of the sunda!
Po i(le %alue $ 0Kcurrency and %alue urrounded (y parenthe e 9 1K i"n hould precede %alue and currency y&(ol9 2K i"n hould follo0 %alue and currency y&(ol9 3K i"n hould i&&ediately precede %alue9 4K i"n hould i&&ediately follo0 %alue9 LC_MAXKnothin" pecified in thi locale.
Mu# !#!n%u1# Supp"( 3tandard &odule gettext for internationali@ation C6,B:D and locali@ation CL,0:D er%ice - (a ed on I:= "ette.t 4P6 X hi"her interface. 3ee doc for e.planation a(out tool u a"e.
7b
7a
2ran lation for e&pty trin" return &eta-data C ee docD. <efine ðod gettext9 lgettext9 ugettext9 ngettext9 lngettext9 ungettext a in NullTranslations interface - a&e rule for return %alue Cstr7unicodeD. ;e a"e tran lation are earched in catalo"9 then in fall(ack if defined9 and if no tran lation i found9 &e a"e it elf i returned Cfor n ðod 9 return in"ular for& if nK1 el e plural for& D.
filter1(fct9se0uence) list" ne
CONTAINERS
1a ic container kind $ -se"uen#es Cordered collection D $ list9 tuple9str9 any itera(le9O -mappings Cunordered key7%alueD $ dictO -sets Cunordered collection D $ set9 frozensetO
list here fct(item) is true3 +one fct 5 bool test on items 1 map (fct,se0uence,) list" ne list here ith item is fct(ith items of se0uence(s)) reduce(fct,se0uence[,initiali/er]) value" fct applied cumulativel! to se0uence items% f(f(f(f(f(initiali/er%a)%b)%c%) zip1(se0uence9) list" list of tuples% ith tuple contains ith items of each se0uences
,
Ope(1 !"ns "n C"n 1!ne(s -or trin" 9 ite& are char . -or &appin" 9 ite& are key . item in container bool" test item container# item not in container bool" test item container# for var in container: O iterate var over items of container len(container) int" count number of items in container$ max(container) value" biggest item in container min(container) value" smallest item in container sum(container) value" sum of items (items must be number1compatible) , -or trin" te t if e.pr i a u( trin" of e?uence. 2 Container &u t pro%ide direct len"th ðod - no "enerator. C"py!n% C"n 1!ne(s <efault container con tructor (uild ne0 container 0ith reference to e.i tin" o(8ect C hallo0 copyD. 2o duplicate content too9 u e tandard &odule copy. 3ee Copyin" #(8ect Cp>D. O3e((!-!n% C"n 1!ne(s Ope(1 !"ns
__len__(self) int" called for len(self) __contains__(self,item) bool" called for item [not] in self Jou can o%erride itera(le protocol on container too.
In-e2!n% = e inde. [i] and lice [i:j[:step]] ynta.. 6nde. @ero-(a ed. :e"ati%e inde. inde.in" fro& end. <efault tep i 19 can u e ne"ati%e tep . 3u(- e?uence inde. (et0een ite& . l = [e1,e2,e3,,en-2,en-1,en] l[0] e1 l[0:n][e1,e2,e3,,en-2,en-1,en] l[1] e2 l[:][e1,e2,e3,,en-2,en-1,en] l[-2] en-1 l[i:][ei+1,ei+2,ei+3,,en-1,en] l[-1] en l[:i][e1,e2,,ei-2,ei-1,ei]
items indexs -n 0 e, 0 -n , -nX, Slice objects <efine inde. ran"e o(8ect 9 u a(le in [] notation. slice([start,]stop[,step]) slice object slice.indices(len) (int{&})" (start,stop,stride) #rdered et of data inde.ed fro& 0. ;e&(er start9 stop9 step. "#ten e Slicin& ;ultiple lice notation - corre pondin" to a election in a &ultidi&en ion data - can (e 0ritten u in" notation like [ a , x:y:z , : , : , : , m:n ]. *llip i notation can (e u ed to fill &ultiple &i in" lice 9 like [ a , x:y:z , ... , m:n ]. 3ee doc . 2hree dot notation ... i replaced internally (y Ellipsis o(8ect. -nX, , e2 2 -nX2 -nX2 2 e> > -nX> item n-2 -2 -2 n-2 en-, n-, -, -, n-, en n
O3e((!-!n% Se5uences Ope(1 !"ns __getitem__(self,index2) value" item at index% called for self[index] __setitem__1(self,index2,value) set item at index to value% called for self[index]=value __delitem__1(self,index2,value) remove item at index% called for del self[index] , #nly for &uta(le e?uence . 2 Para&eter inde. can (e a lice ' tart9 top9 tep) - replace old UU"et liceUU9 UU et liceUU9 UUdel liceUU. Can al o o%erride arith&etic operation __add__ Cconcatenation D and __mul__ Crepetition D9 container operation and o(8ect operation .
MAPPINGS 9DICTIONARIES:
1uiltin type dict. 3tore key$%alue pair . <eclare a dictionary $ { ke!:value [,]} {} dict() dict" empt! dictionar! (like {}) dict(**k args) dict" from named parameters and their values dict(iterable) dict" from (ke!%value) b! iterable dict(otherdict) dict" duplicated fro another one (first level)
Ope(1 !"ns "n M1pp!n%s 3ee #peration on Container CpBD too9 con iderin" operation on key . d[ke!] value for ke!# d[ke!]=value set d(ke!6 to value del d[ke!] removes d(ke!6 from d# d.fromkeys(iterable[,value5None)D dict" ith ke!s from iterable and all
same value d.clear() removes all items from d d.copy() dict" hallo cop! of d d.has_key(k) bool" test ke! presence 1 same as k in d d.items() list" cop! of d)s list of (ke!% item) pairs d.keys() list" cop! of d)s list of ke!s d.update(otherd) cop! otherd pairs into d d.update(iterable) cop! (ke!%value) pairs into d d.update(**k args) cop! name5value pairs into d d.values() list" cop! of d)s list of values d.get(ke!,defval) value" d(ke!6 if ke!d% else defval d.setdefault(ke![,defval5None]) value" if ke!d set d(ke!65defval% return d(ke!6 d.iteritems() iterator over (ke!% value) pairs d.iterkeys() iterator over ke!s d.itervalues() iterator over values d.pop(ke![,defval]) value" del ke! k and returns the corresponding value3 Jf ke! is not found% defval is returned if given% other ise KeyError is raised d.popitem() removes and returns an arbitrar! (ke!% value) pair from d
,
slicing indexs
SE8UENCES
3e?uence are ordered collection $ str9 unicode9 list9 tuple9 buffer, xrange, array.array any user class defining se)uences interface, or any iterable data.
L!s s ) Tup#es 1uiltin type list and tuple tore e?uence of any o(8ect . Li t are &uta(le9 tuple are i&&uta(le. <eclare a li t $ [item[,]] <eclare a tuple $ (item[,]) *otes + [] empty list (() empty tuple ( (item,) one item tuple. list(object) list" ne list (cast from object , duplicate existing) tuple(object) tuple" ne tuple (cast from object , duplicate existing) range([start,]stop[,step]) [int]" list% arithmetic progression of integers xrange1([start,]stop[,step]) xrange" object generating arithmetic
progression of integers
=nle u in" a e?uence a a &appin" key9 or en urin" it i i&&uta(le data9 prefer list to tuple. , = e in place of ran"e to a%oid (uildin" hu"e li t 8u t for inde.in".
Ope(1 !"ns "n Se5uences 3ee #peration on Container CpBD too. se0# + se0$ concatenation of se0# and se0$
se0uence * n concatenation of se0uence duplicated n times n * se0uence concatenation of se0uence duplicated n times
reversed(se0uence) iterator throught se0uence in reverse order sorted(se0uence[,cmp[,ke![,reverse]]]) list" ne list% sorted items from
iterable 1 see list3sorted
Ope(1 !"ns "n &u 1/#e se5uences ;uta(le e?uence Ce.. listD can (e &odified in place. Can u e &uta(le e?uence inde.in" in left part of a i"n&ent to &odify it ite& $ se0[index]=expr M se0[start:stop]=expr M se0[start:stop:step]=expr se0.append(item) add item at end of se0uence se0.extend(otherse0) concatenate otherse0 at end of se0uence se0.count(expr) int" number of expr items in se0uence se0.index(expr[,start[,stop]]) int" first index of expr item se0.insert(index,item) item inserted at index se0.remove(expr) remove first expr item from se0uence se0.pop([index]) item" remove and return item at index (default 1#) se0.reverse() items reversed in place se0.sort([cmp][,key][,reverse]) items sorted in place 1 cmp " custom comparison fct(a%b)% retval <4 or 5 4 or >4 1 key " name of items attribute to compare 1 reverse " bool del se0[index] remove item from se0uence del se0[start:stop[:step]] remove items from se0uence
8b
O3e((!-!n% M1pp!n% Ope(1 !"ns __getitem__(self,key) value for ke!% called for self[key] __setitem__(self,key,value) set value for ke!% called for self[key]=value __delitem__(self,key,value) remove value for ke!% called for del self[key] Can al o o%erride container operation and o(8ect operation . O 'e( M1pp!n%s -or on-di k &appin" 9 ee tandard &odule shelve9 and data(a e &odule . -or ordered &appin" ee third party &odule OrderedDict.
8a
8c
SETS
=nordered collection of uni?ue ite& . -ro@en et are i&&uta(le once created. set([iterable]) set" using values from iterable frozenset([iterable]) frozenset" using values from iterable
a.fromlist(list) extend arra! from values in list a.tolist() list" items in a list a.fromstring(s) extend arra! from values in binar! buffer s (string) a.tostring() str" items in binar! representation a.fromunicode(s) extend )u) arra! from data in unicode sting a.tounicode() unicode" convert )u) arra! to unicode string
,
izip(iterable[,]) iterator over tuple(items at same index from iterables) repeat(object[,count]) iterator returning object over and over again% up to starmap(function,iterable) iterator over function(<tuple item from iterable) takewhile(predicatefct,iterable) iterator over items of iterable here
predicatefct(item) is true count times (default to infinite)
Ope(1 !"ns "n Se s 3ee #peration on Container CpBD too. s.issubset(others) bool" test s others s.issuperset(others) bool" test others s s.add(item) adds item to set s.remove(item) removes item from set# s.clear() removes all items from (not for/en) set s.intersection(others) set" s others s & others set" s others s.union(others) set" s others s | others set" s others s.difference(others) set" (x , xs and xothers6 s - others set" (x , xs and xothers6 s.symmetric_difference(others) set" (x , xs xor x others6 s ^ others set" (x , xs xor x others6 s.copy() shallo cop! of set s.update(iterable) adds all values from iterable to set , Rai e /ey*rror if o(8ect not in et. Re ult set ha%e a&e type a s o(8ect Cset7frozensetD.
6f le ite& than needed9 "et a%aila(le one then rai e EOFError. #ld ðod read and 0rite replaced (y fro&file and tofile.
8ueue 3tandard &odule collections pro%ide ?ueue &ana"e&ent. deque([iterable]) deque" initiali/ed from iterable 0.append(x) add x to right side of de0ue 0.appendleft(x) add x to left side of de0ue 0.clear() remove all elements from de0ue 0.extend(iterable) extend right side of de0ue 0.extendleft(iterable) extend left side of the de0ue 0.pop() item" pop and return item from de0ueue right side 0.popleft() item" pop and return item from de0ueue left side 0.rotate(n) rotate de0ue from n steps% to right if n>4% to left if n<4 Can al o u e tandard operation on e?uence $ len(0), reversed(0), copy.copy(0)9 copy.deepcopy(0)9 item in 09 0[-1]9 and eriali@ation %ia picklin" protocol. P(!"(! y 8ueues 3tandard &odule heapq. 3tructure a li t a a priority ?ueue. heapify(x) x list transformed into heap heappush(heap,item) push item onto heap heappop(heap) item" pop and return smallest item from the heap heapreplace(heap,ne item) item" pop and return smallest item from the
heap% push ne item nlargest(n,iterable) list" n largest from iterable
tee(iterable',n)) n independent iterators from same iterable'% default n5$ , Iroup of ite& i internally u ed - &u t a%e it a li t if needed after current iteration. 2 3top at end of horter itera(le. > 3lice para&eter cannot (e ne"ati%e. 4 <onPt u e itera(le out of tee created iterator .
DATE ) TIME
M"-u#e !&e 3tandard &odule time define co&&on function and data.
0ate 1 )ime 0ata float/time 2 float containin" econd fro& PepochP C8anuary , ,EA0 on =ni. - ee gmtime(0)D9 0ith u(- econd preci ion in deci&al part. tuple/time K tuple containin" E int C ee ta(leD. struct_time K tuple7o(8ect 0ith int attri(ute C ee ta(leD.
% 0 , 2 > 4 att!ibute value
% 5 6 A B
att!ibute
value
float/ elay 2 float containin" econd 9 0ith u(- econd preci ion. <32 i local ti&e9 =2C i uni%er al CI;2D ti&e. accept2dyear (r 6 bool" accept t o1digit !ear values (default true)%
modifiable via environment var .K-LD+K$M
A((1y 3tandard &odule array pro%ide efficient array of (a ic type . 6t u e co&pact tora"e for ele&ent of a&e type.
)ype Co es
n t# $ type py type n t# $ py type
, , 2 2 4 4
'b' i"ned char 'c' char 'h' i"ned hort 'i' i"ned int 'l' i"ned lon" 'f' float +unctions
, 2 2 2 4 B
un i"ned char unicode char un i"ned hort un i"ned int un i"ned lon" dou(le
S"( e- L!s 3tandard &odule bisect &aintain li t orted C%ia (a ic (i ection al"oD. bisect_left(list,item[,lo[,hi]]) int" index to insert item at leftmost sorted
bisect_right(list,item[,lo[,hi]]) int" index to insert item at rightmost
sorted position# position#
altzone int" offset (pos,neg) in seconds of NI- relativel! to =-*% in daylight int" 4 if a NI- time/one is defined timezone int" offset (pos,neg) in seconds of local (non NI-) time/one tzname (str{$})" names of local time/one (non1NI-% NI-) +unctions asctime([t5$]) str" build local time string from t (tuple_time or struct_time) clock() float" processor time in seconds% for accurate relative time ctime([secs5$]) str" build local time string from float_time second gmtime([secs5$]) struct_time" convert float_time to =-* struct_time localtime([secs5$]) struct_time" convert float_time to NI- struct_time mktime(t) float_time" convert NI- t (tuple_time or struct_time) to float_time 1 ma! raise OverflowError or ValueError sleep(secs) execution suspended during secs (float_dela!) times% ma!be
less (signal catching)% ma! be more (process,threads scheduling) measurement seconds% use onl! if da!light is true
nK i@e in (yte 9 tcKchar typecode to u e array(tc9[iterable]) array" ith t!pecode tc% initiali/ed from iterable a.typecode str" t!pecode of the arra! a.itemsize int" b!tes si/e of one arra! data a.append(expr) append item expr to end of arra! a.extend(arra!) append items from another arra! a.count(expr) int" number of expr items in arra! a.index(expr) int" first index of expr item a.insert(index,expr) expr item inserted at index a.remove(expr) remove first expr item from arra! a.pop([index]) value" return and remove item at index (default 1#) a.reverse() items in arra! are reversed a.buffer_info() (int{$})" current storage infos (address%items count) a.byteswap() s ap b!tes of arra! items a.fromfile(f,n) append n items read from real binar! file f# a.tofile(f) rite all items to real binar! file f 9a
bisect(O) >lias for bisect_right(O) insort_left(list,item[,lo[,hi]]) !nsert item at leftmost sorted position# insort_right(list,item[,lo[,hi]]) !nsert item at rightmost sorted position# insort(O) >lias for insort_right(O) , Fith li t pre%iou ly orted.
I e(1 !"n T""#s 3tandard &odule itertools pro%ide o&e practical iterator . chain(iterable[,O]) iterator over items of several iterables count([start]) iterator over integers from start (default 4) cycle(iterable) iterator c!cling over iterable items dropwhile(predicatefct,iterable) iterator over items of iterable here
predicatefct(item) is false
here ke!fct(item)5ke! value)% default ke!fct is identit! ifilter(predicate,iterable) iterator over items of iterable here predicatefct(item) is true 1 +one predicate filter items being true ifilterfalse(predicate,iterable) iterator over items of iterable here predicatefct(item) is false 1 +one predicate filter items being false imap(function,iterable[,]) iterator over function(items at same index from iterables$)% +one function return tuples items isliceCiterable,[start,]stop[,step]) iterator over items at slice& indexs from iterable% +one stop goes up to end
strftime(format[,t5$]) str" build time string from t (tuple_time or struct_time) using format string (table infra) 1 ma! raise ValueError strptime(string[,format]) struct_time" parse string using time format# 1 ma! raise ValueError time() float_time" current =-* time tzset() resets time conversion rules accordingl! to environnment variable
-? 1 unix onl!% see docs
,
<efault for&at QZa Z( Zd ZG$Z;$Z3 ZJQ. ;i in" %alue default to C,E009 ,9 ,9 09 09 09 09 ,9 -,D 2 Para& secs default to current ti&e9 para& t default to local current ti&e. 9c
9b
f.readlines() [string]" list of all lines read from file% end of lines removed
4((re%iated 0eekday na&e,. 4((re%iated &onth na&e,. 4ppropriate date and ti&e repre entation,. Gour '0092>).
%A %B %d
-ull 0eekday na&e,. -ull &onth na&e,. ;onth day '0,9>,). Gour '0,9,2). ;onth '0,9,2). 4; or P; . Jear 0eek '0095>) C3unday (a edD. Jear 0eek '0095>) C;onday (a edD. 4ppropriate ti&e repre entation,. Jear C0ith centuryD. Literal Z char.
,
f.seek(offset[, hence=0]) modif! current position in file 1 start% 1 from current% 2 from end f.tell() int" current position in file f.write(string) data ritten to file f.writelines(listofstrings) data
%I Jear day '00,9>66). %m ;inute '0095E). %p 3econd '0096,). %U Feek day '096) C0K3undayD. %W 4ppropriate date repre entation,. %X Jear '009EE). %Y 2i&e @one na&e Cno character if %%
no ti&e @one e.i t D.
for line in f :O iterate over lines of f #ld ðod xreadlines replaced (y iteration on file o(8ect. -or opti&i@ed direct acce to rando& line in te.t file 9 ee &odule linecache. Attributes
f.closed bool" indicator file has been closed f.encoding str,None" file content encoding f.name str" name of the file f.newlines str,tuple of str,None" encountered ne lines chars f.softspace bool" indicator to use soft space ith print in file
P!pes -or tandard proce redirection u in" pipe 9 ee al o 3i&ple *.ternal Proce Control Cp,4D. os.pipe() ((int{$}){$})" create pair (fdmaster%fdslav) of fd (read% rite) for
os.mkfifo(path[,mode54PPP]) create named pipe path 1 mode masked out
ith umask 1 don)t open it (=nix) a pipe
In-&e&"(y F!#es
Memory 'uffer +iles = e tandard &odule StringIO and cStringIO to (uild file-like o(8ect torin" data in &e&ory. f = StringIO.StringIO() 1uild a file-like in &e&ory. f.write(string) data ritten to file f.other file riting methods f.getValue() str" current data ritten to file f.close() file no longer usable% free buffer c3trin"6# i a co&piled C&ore efficientD %er ion of 3trin"6# for 0ritin". #ptional ar"u&ent allo0 to (uild &e&ory file to read fro& too. f = cStringIO.StringIO([string]) f.read(6s!7e=) str" block of data read from )file) (string) f.other file reading methods Memory Mappe +iles 3OS le%el4 3tandard &odule mmap &ana"e &e&ory-&apped file 9 u a(le a file-like o(8ect and a &uta(le trin"-like o(8ect . 2o (uild a &e&ory &ap $ mm = mmap.mmap(fileno,length[,tagname[,access]]) ( indo s6 mm = mmap.mmap(fileno,length[,flags[,prot[,access]]]) (unix6 = e an o file de criptor Cfro& os.open() or fro& file-o(8ectP fileno()D for a file opened for update. Len"th pecify a&ount of (yte to &ap. #n 0indo0 9 file &ay (e e.tended to that len"th if it i horter9 it canPt (e e&pty9 and 0 corre pond to &a.i&u& len"th for the file. 4cce Ckey0ord para&D $ ACCESS_READ CreadonlyD9 ACCESS_WRITE C0rite-throu"h9 default on Findo0 D9 or ACCESS_COPY Ccopy-on0riteD. #n Findo0 9 ta"na&e allo0 to identify different &appin" a"ain t a&e file Cdefault to :oneD. #n =ni.9 fla" $ MAP_PRIVATE Ccopy-on-0rite pri%ate to proce D or MAP_SHARED CdefaultD. 4nd prot C&e&ory protection &a kD $ PROT_READ or PROT_WRITE9 default i PROT_READ|PROT_WRITE. 6f u e protXfla" para& 9 donPt u e acce para&. mm.close() mmap file no longer usable mm.find(string[,start50]) int" offset , -1 mm.flush([offset,si/e]) rite changes to disk mm.move(dest,src,count) cop! data in file mm.read([si/e]) str" block of data read from mmap file# mm.read_byte() str" next one b!te from mmap file# mm.readline() str" next line read from file% Qend of line removedQ# mm.resize(ne si/e) ritable mmap file resi/er mm.seek(offset[, hence=0]) modif! current position in mmap file 1 hence " 0 from start% 1 from current% 2 from end mm.size() int" length of the real os file mm.tell() int" current position in mmap file mm.write(string) data ritten to mmapfile# mm.write_byte(b!te) str of one char (b!te) data ritten to mmap file# 10c
M"-u#e -1 e !&e 3tandard &odule datetime ha tool for date7ti&e arith&etic 9 data e.traction and &anipulation. <efine cla $ timedelta9 time9 date9 datetime9 [tzinfo]. M"-u#e !&e! 3tandard &odule timeit ha function to &ea ure proce in" ti&e of code. 6t can (e u ed in cript C ee doc D9 or directly in co&&and line $ python &mtimeit [-n +] [-r +] [- I] [-t] [-c] [-h] [statement []] -n + / --nu&(erK+ e.ecute statement + ti&e repeat ti&er + ti&e Cdefault >D -r + / --repeatK+ - I / -- etupKI e.ecuted I once initially Cdefault passD -t / --ti&e u e time.time() Cdefault e.cept Findo0 D -c / --clock u e time.clock() Cdefault on Findo0 D print ra0 ti&in" re ult - &ay repeat option -% / --%er(o e print help and e.it -h / --help O 'e( M"-u#es 3tandard &odule calendar ha function to (uild calendar . 3ee al o third party &odule mxDateTime.
L"<-#e3e# F!#es 1a e lo0-le%el function are in tandard &odule os. Careful of cla h 0ith (uiltin 0ith os.open na&e.
open(file,flags[,mode54BBB]) int" fd% open file 1 see flags infra 1 mode fdopen(fd[,mode[,bufsi/e]]) file" build a file connected to fd 1 mode and bufsi/e as for builtin open()+ mode must start ith r or w or a dup(fd) int" fd% duplicate file descriptor dup2(fd,fd$) int" fd% duplicate file descriptor into fd$% previousl! closing fd$
if necessar! close(fd) close file descriptor masked out ith umask
read(fd,n) str" read as most n b!tes from fd file 1 return empt! string if end
of file reached
write(fd,str) int"
ritten
FILES
:or&al file operation u e Python file o(8ect Cor file-like o(8ect 0ith a&e interfaceD. 3o&e function directly &anipulate file path na&e C trin" D. -unction &appin" lo0 le%el #3 handler C&ainly tho e in tandard os &oduleD u e nu&eric file de criptor Cfd al o kno0n a filenoD. Ra0 data u e str type Ccan contain any data (yte %alue 9 includin" 0D.
lseek(fd,pos,ho ) set file descriptor position 1 ho " 0 from start% 1 from current% 2 from end fdatasync(fd) flush file data to disk 1 don)t force update metadata (=nix) fsync(fd) force lo level DI buffers to be ritten ftruncate(fd,length) truncate file descriptor to at most length (=nix) Open +la&s Con tant defined in os &odule9 u e (it-0i e #R Cx y zD to &i. the&. O_RDONLY read onl! O_WRONLY rite onl! O_RDWR read, rite O_APPEND append each rite to end O_CREAT create ne file (remove existing) O_EXCL ith O_CREAT% fail if file exist (=nix) O_TRUNC reset existing file to /ero si/e O_DSYNC xxxxxx (=nix) O_RSYNC xxxxxx (=nix) O_SYNC return from JD hen data are ph!sicall! ritten (=nix) O_NDELAY return immediatl! (don)t block caller during JD) (=nix) O_NONBLOCK same as O_NDELAY (=nix) O_NOCTTY terminal device file can)t become process tt! (=nix) O_BINARY don)t process end of lines (cf7lf from,to cr) (Oindo s) O_NOINHERIT xxxxxx (Oindo s) O_SHORT_LIVED xxxxxx (Oindo s) O_TEMPORARY xxxxxx (Oindo s) O_RANDOM xxxxxx (Oindo s) 10b
F!#e O/0ec s 3tandard file type i (uiltin file. 6t define the Python file protocol. Create a file $ file(filename[,mode5'r'[,bufsi/e]]) file object ;ode fla" Cco&(ina(leD $ 'r' read9 'w' 0rite ne09 'a' 0rite append9 '+' update9 'b' (inary,9 'U' uni%er al ne0line2. 1uffer i@e $ 0 un(uffered9 1 line (uffered9 !, around that i@e. #penCD i an alia for fileCD , <efault te.t &ode trie to interpret ne0line e?uence in the file. 2 4uto&atically choo e ne0line e?uence in CR or L- or CRXL- adapted fro& file7to platfor&.
Metho s an +unctions
f.close() file flushed and no longer usable f.fileno() int" lo f.flush() buffers level file descriptor (fd) ritten to file on disk
f.isatty() bool" indicator file is a terminal f.read([si/e]) str" block of data read from file f.readline() str" next line read from file% end of line removed
10a
F!#es In."(&1 !"ns -unction to et7"et file infor&ation are in os and in os.path &odule9 o&e in shutil &odule. Con tant fla" are defined in tandard stat &odule. 3o&e function acce in" proce en%iron&ent data Ce.. current 0orkin" directoryD are docu&ented in Proce ection. os.access(path,mode) bool" test for path access ith mode using real uid,gid 1 mode in F_OK% R_OK% W_OK% X_OK os.F_OK access mode to test path existence os.R_OK access mode to test path readable os.W_OK access mode to test path ritable os.X_OK access mode to test path executable os.chmod(path,mode) change mode of path 1 mode use stat.S_*
constants
st_mode st_ino st_dev st_nlink st_uid st_gid st_size st_atime st_mtime st_ctime st_blocks st_blksize st_rdev st_rsize st_creator st_type
os.ttyname(fd) str" terminal device associated to fd (=nix) os.isatty(fd) bool" test file descriptor is a tt!1like (=nix) os.tcsetpgrp(fd,pg) set process group id associted ith terminal fd os.tcgetpgrp(fd) int" process group associated
(=nix) ith terminal fd (=nix)
3ee al o tandard &odule tty and pty. -or u er-interface control on te.t ter&inal 9 ee tandard packa"e curses and it u(-&odule .
os.chown(path, uid, gid) change path o ner and group (=nix) os.lchown(path, uid, gid) change path o ner and group 1 don)t follo
s!mlinks(=nix) os.fstat(fd) int" status for file descriptor
Te&p"(1(y F!#es = e tandard tempfile &odule. 6t define e%eral function to &ake life ea ier and &ore ecure. TemporaryFileC[mode5) 7b)[,bufsi/e51#[,suffix[,prefix[,dir]]]]]) file,file1like" temp file 1 removed on close 1 not necessar! visible in file1 s!stem 1 dir and prefix as for mkstemp NamedTemporaryFileC[mode5) 7b)[,bufsi/e51#[,suffix[,prefix[,dir]]]]]) file,file1like" like TemporaryFile 1 file visible in file1s!stem mkstemp([suffix[,prefix[,dir[,text]]]]) (int,str)" (fd%path) of ne
temporat! file 1 no race condition 1 onl! creator can read, rite 1 no executable bit 1 not automaticall! deleted 1 binar! mode unless text specified mkdtemp([suffix[,prefix[,dir]]]) str" path of ne temporar! director! created 1 no race condition 1 onl! creator can read, rite,search 1 not automaticall! deleted> gettempdir() str" default director! for temporar! files
os.stat(path) stat structure object" file s!stem informations (=nix) os.lstat(path) stat structure object" file s!stem informations (=nix) 1 dont os.stat_float_times([ne value]) bool" test,set stat function time
stamps data t!pe 1 avoid setting ne containing path (=nix) value follo s!mlinks
statvfs_result i returned (y fstatvfsand statvfs function 9 u a(le a a tuple Cu e statvfs %aria(le inde. D and a an o(8ect 0ith attri(ute $
% 0 , 2 > 4 5 6 A B E att!ibute inde' va!
os.statvfs(path) statvfs_result" informations about file s!stem os.utime(path,times) set access and modification times of file path 1
times5(atime%mtime) (numbers) 1 times5+one use current time os.fpathconf(fd,name) str , int" s!stem configuration information about file referenced b! file descriptor 1 see platform documentation and pathconf_names variable 1 name str or int (=nix)
f_bsize f_frsize f_blocks f_bfree f_bavail f_files f_ffree f_favail f_flag f_namemax
F_BSIZE F_FRSIZE F_BLOCKS F_BFREE F_BAVAIL F_FILES F_FFREE F_FAVAIL F_FLAG F_NAMEMAX
usage preferred file y te& (lock i@e funda&ental file y te& (lock i@e total nu&(er of (lock in the file y te& total nu&(er of free (lock free (lock a%aila(le to non- uper u er total nu&(er of file node total nu&(er of free file node free node a%aila(le to non- uper u er fla" - ee ho t tat%f CD &an pa"e &a.i&u& file na&e len"th
gettempprefix() str" default filename prefix for temporar! files #ther function in tempfile and os &odule are kept for code co&pati(ility9 (ut are con idered not enou"h ecured. 4l o tempdir and template data in tempfile - 0hich hould not (e u ed directly.
os.pathconf_names dict" name index 1 names accepted b! pathconf and fpathconf corresponding index on host (=nix) os.path.exists(path) bool" test existing path 1 no broken s!mlinks os.path.lexists(path) bool" test existing path 1 allo broken s!mlinks os.path.getatime(path) float_time" last access time of path os.path.getmtime(path) float_time" last modification time of path os.path.getctime(path) float_time" creation time ( indo s) or last
modification time (unix) of path
Stat Constants <efined in tandard stat &odule. S_ISUID xxxxx S_ISGID xxxxx S_ENFMT xxxxx S_ISVTX xxxxx S_IREAD 44'44 user can read S_IWRITE 44$44 user can rite S_IEXEC 44#44 user can execute S_IRWXU 44B44 user can read7 rite7execute S_IRUSR 44'44 user can read S_IWUSR 44$44 user can rite S_IXUSR 44#44 user can execute S_IRWXG 444B4 group can read7 rite7execute S_IRGRP 444'4 group can read S_IWGRP 444$4 group can rite S_IXGRP 444#4 group can execute S_IRWXO 4444B ever!bod! can read7 rite7execute S_IROTH 4444' ever!bod! can read S_IWOTH 4444$ ever!bod! can rite S_IXOTH 4444# ever!bod! can execute 11b
os.path.getsize(path) int" b!tes si/e of path file os.path.isabs(path) bool" test absolute os.path.isfile(path) bool" test regular file (follo s!mlinks) os.path.isdir(path) bool" test existing director! (follo s!mlinks) os.path.islink(path) bool" test s!mlink os.path.ismount(path) bool" test mount point os.path.samefile(path#,path$) bool" test refer to same real file os.path.sameopenfile(f#,f$) bool" test opened files refer to same real
file (unix%macos) (unix%macos)
P1 ' M1n!pu#1 !"ns Path &anipulation function are in tandard os.path &odule. supports_unicode_filenames <bool" unicode usable for file names> abspath(path) str" normali/ed absoluti/ed pathname basename(path) str" file name part of path commonprefix(pathlist) str" longest common path prefix (char1b!1char) dirname(path) str" director! name of pathname join(path[,O]) str" concatenate path components normcase(path) str" normali/e path case for platform (see doc) normpath(path) str" normali/e path (,, ,3, ,33,)% on indo s / realpath(path) str" canonical path (remove s!mlinks) (unix) split(path) (str{$}): split into (head% last pathname component) splitdrive(path) (str{$}): split into (drive% tail) splitext(path) (str{$}): split into (root% ext)
Host Specific !ath 0ata sys.getfilesystemencoding() <name of encoding used b! s!stem for
filenames>
os.path.samestat(stat#,stat$) bool" test stat tuples refer to same file shutil.copymode(srcpath,dstpath) cop! normal file permission bits shutil.copystat(srcpath,dstpath) cop! normal file permission bits and
last access and modification times (unix%macos)
-ollo0in" data are in os and in os.path. curdir str" string used to refer to current director! pardir str" string used to refer to parent director! sep str" char used to separate pathname components altsep str" alternative char used to separate pathname components extsep str" char used to separate base filename from extension pathsep str" conventional char to separate different paths
Stat Structures stat_result i returned (y stat and lstat function 9 u a(le a a tuple 11a
D!(ec "(!es os.listdir(path) [str]*[unicode]" list names in path director! 1 ithout . and .. 1 arbitrar! order 1 path string t!pe item strings t!pe os.mkdir(path[,mode54BBB]) create director! path 1 mode masked out
11c
ith umask
os.removedirs(path) remove directories% recursivel! os.walk(top[,topdo n5True [,onerror5+one]]) iterable" go throught dirs
under top% for each dir !ield tuple(dirpath% dirnames% filenames) 1 onerror5fct(os3error) 1 see docs os.path.walk(path,visit,arg) call visit(arg%dirname%names) for dirs rooted at path 1 ma! modif! names (files list) to influence alk% ma! prefer to use
codecs.BOM_UTF32 str" alias for BOM_UTF32_LE or BOM_UTF32_BE codecs.BOM_UTF32_BE str" '\x00\x00\xfe\xff' codecs.BOM_UTF32_LE str" '\xff\xfe\x00\x00' 3ee *ncodin" - <ecodin" Cp,>D for detail a(out encoding and errors.
option 1 ma! raise NoSectionError rp.remove_section(section) bool" return True if there as such section rp.optionxform(option) str" normali/ed internal form of option
-ormal Interface
cp.get(section,option[,ra [,vars]])string" value for option in section 1 % interpolation expanded unless ra is true 1 vars is a dict of additional defaults 1 reference expansion names are processed b! optionxform() for matching cp.items(section[,ra [,vars]]) [(name,value)]" for given section 1 ra and vars as in get()
os.walk
Se(!1#!71 !"n 3tandard &odule pickle and cPickle C peed up to ,000.D ha%e upport for data eriali@ation of o(8ect hierarchie . 3ee Python docu&entation. 3ee al o &odule marshal Cread70rite of Python data in platfor& independant (inary for&at - (ut can (roke for&at (et0een relea e D. Pe(s!s ence 3tandard &odule shelve u e picklin" protocol to tore o(8ect in <1; file C ee p,AD and acce the& %ia a dictionnary-like interface 0ith key a str. open(filename[,flag[,protocol[, riteback[,binar!]]]]) dictionar!1like object 1 flag as anydbm.open (p#B)% default to 'c' 1 protocol default to 0 (ascii
format) 1 riteback" cache accessed entries in memor! and ritten them back at close time% default to False 1 binar! is deprecated% use protocol3
Spec!1# F!#es os.link(src,dst) create hard link named dst referencing src (=nix) os.symlink(src,dst) create s!mbolic link named dst pointing to src (=nix) os.readlink(path) str" path pointed to b! s!mbolic link os.mknod(path[,mode54PPP,device]) create AI node (file% device special file% named pipe) 1 mode 5 permissions | nodet!pe 1 node t!pe in S_IFREG% S_IFREG% S_IFCHR% S_IFBLK% and S_IFIFO defined in stat module os.major(device) int" ra device major number os.minor(device) int" ra device minor number os.makedev(major,minor) compose ra device from major and minor
numbers>
Safe Interface
sp.set(section9option9value) set value string for section and option
"#ceptions CExceptionD Error ParsingError NoSectionError DuplicateSectionError MissingSectionHeaderError NoOptionError InterpolationError InterpolationDepthError InterpolationMissingOptionError InterpolationSyntaxError -or i&ilar file for&at upportin" ne ted u( ection 9 ee ConfigObj confi" par er. -or 0indo0 u er 9 tandard &odule _winreg. -or te.t-file confi" 9 can u e H;L tool 9 and ee al o third party J4;L par er like PyYaml.
C"py!n%, M"3!n%, Re&"3!n% os.remove(path) remove file path (not director!) os.rename(src,dst) rename src to dst 1 on same files!stem1 ma! remove
existing dst file
os.renames(old,ne ) rename old to ne % recursivel! 1 tr! to create os.unlink(path) remove file path (not director!) 1 same as remove 3tandard &odule shutil pro%ide hi"h le%el function on file and directorie . copyfile(src,dst) cop! normal file content 1 over rite destination$3 copyfileobj(fsrc,fdst[,length5#Pkb]) cop! file1like object content b!
blocks of length si/e (<45one chunk) intermediate directories
C"n.!%u(1 !"n F!#es 3tandard &odule ConfigParser. 6t u e tandard .!"! file to tore confi"udation data $ [section] +alue can contain %(name)s reference 0hich &ay (e e.panded u in" %alue in a&e ection or name:value in defaults name=value # and ; tart co&&ent line . 2he &odule define three confi"uration cla e 0ith different data acce le%el $ RawConfigParser ConfigParser SafeConfigParser rp=RawConfigParser([defaults]) RawConfigParser cp=ConfigParser([defaults]) ConfigParser sp=SafeConfigParser([defaults]) SafeConfigParser 6n the three con tructor 9 defaults i a dict of option$%alue for reference e.pan ion. MAX_INTERPOLATION_DEPTH int" max recursive depth for get() hen ra
DEFAULTSECT str" name of defaut section ,aw Interface
rp.defaults()dict" default values for references expansion rp.sections()[string]" list sections in config ( ithout NFA>=E-) rp.add_section(sectionD add a ne section 1 ma! raise parameter is false
EXCEPTIONS
3tandard e.ception defined in exceptions &odule9 and a%aila(le in current cope. 4ll e.ception &u t (e u(cla e of Exception root cla . = e tandard e.ception if their &eanin" corre pond to you error . 3u(cla tandard e.ception 0hen needed.
copytree(src,dst[,s!mlinks5False]) recursivel! cop! director! tree 1 destination must be ne 1 files copied via copy 1 if s!mlinks is Aalse% cop!
s!mbolic links files content% else just make s!mbolic links3
#
director! tree 1 onerror5fct(fctref% path% excinfo)3# move(src,dst) recursivel! move file or director! tree 1 ma! rename or cop!3#
, 2
;ay rai e shutil.Error e.ception. Para& rc and d t are file path na&e .
Enc"-e- F!#es 3tandard &odule codecs ha%e function and o(8ect to tran parently proce encoded file Cu ed internally a unicode file D. codecs.open(filename,mode[,encoding[,errors[,buffering]]]) <file1like EncodedFile object ith transparent encoding,decoding> codecs.EncodedFile(file,input[,output[,errors]]) <file1like rapper
around file% decode from input encoding and encode to output encoding> codecs.BOM str" alias for BOM_UTF16
DuplicateSectionError rp.has_section(section)bool" test if section exists 1 cant test for NFA>=Erp.options(section)[string]" list options in section rp.has_option(section,option)bool" test if section and option exists rp.readC[filename],filenameD[filename]" tr! to load configuration data from
files (continue if fail) 1 return names of loaded files rp.readfp(fp[,filename]) load configuration data from file,file1like rp.get(section,option)str" option value rp.getint(section,option)int" coerce option value to int rp.getfloat(section,option)float" coerce option value to float rp.getboolean(section,option)bool" coerce option value to bool 1 True is strings 1 yes true on 1 False is strings 0 no false off 1 ma! raise rp.items(section)[(name,value)]" options in the section rp.set(section,option,value) set option to string value in section 1 ma! raise NoSectionError rp.write(fileobject) rite configuration data to file as such rp.remove_option(section,option) bool" return True if there
codecs.BOM_BE str" alias for BOM_UTF16_BE codecs.BOM_LE str" alias for BOM_UTF16_LE codecs.BOM_UTF8 str" '\xef\xbb\xbf' codecs.BOM_UTF16 str" alias for BOM_UTF16_LE or BOM_UTF16_BE codecs.BOM_UTF16_BE str" '\xfe\xff' codecs.BOM_UTF16_LE str" '\xff\xfe' 12a
ValueError
S 1n-1(- E2cep !"n C#1sses Exception StopIteration , iteratorP ne.tCD9 no &ore %alue. SystemExit , y .e.itCD called StandardError , (uilt-in e.ception ArithmeticError , arith&etic error . FloatingPointError OverflowError ZeroDivisionError AssertionError , assert cond[,message] fails. AttributeError , attri(ute et7"et fail. EnvironmentError , host system error & see arg tuple attribute IOError OSError WindowsError , -indows error codes. EOFError , end-of-file 0ith input() or raw_input(). ImportError KeyboardInterrupt , user interrupt CCtrl-CD. LookupError IndexError , non&e.istent se)uence inde.. KeyError , non-e.i tent &appin" key. MemoryError NameError , non&e.istent name in current scope. UnboundLocalError , reference to an una i"ned local %aria(le. ReferenceError , try acce in" 0eak-ref di po ed o(8ect. RuntimeError , prefer defining ad&hoc subclasses).
12c
12b
NotImplementedError SyntaxError IndentationError TabError SystemError , a bug in /ython. TypeError ValueError , good type, but bad value. UnicodeError Warning , 0arnin" upercla C ee Farnin" infraD UserWarning PendingDeprecationWarning DeprecationWarning SyntaxWarning RuntimeWarning
activeCount() int" number of currentl! active threads currentThread() Thread" current running thread enumerate() [Thread]" list of active threads settrace(func) install trace function called before threads run methods setprofile(func) install profile function called before threads run
methods
evt.isSet() bool" value of event internal flag evt.set() set event internal flag to true 1 unlock evt.clear() set event internal flag to Aalse evt.wait([timeout]) ait for event internal flag to be true 1 timeout is a float_dela! (default to +one5infinite blocking) aiting threads
3tandard &odule thread upport lo0 le%el thread &ana"e&ent. = e &odule dummy_thread and dummy_threading on platfor& 0ithout &ultithreadin".
W1(n!n%s Farnin" &u t (e u(cla e of Warning root cla . 3tandard warnings &odule control proce in" of 0arnin" e.ception . warn(message[,categor![,stacklevel]]) warn_explicit(message,categor!,filename,lineno[,module[,registr!]]) showwarning(message,categor!,filename,lineno[,file]) formatwarning(message,categor!,filename,lineno) filterwarnings(action[,message[,categor![,module[,lineno[!append]]]]]) resetwarnings() sys.warnoptions E2cep !"ns P("cess!n% sys.exc_info() (t!pe,value,traceback) for current exception#> sys.exc_clear() current exception related informations cleared sys.excepthook (r ) fct(t!pe% value% traceback) called for uncaught
sys.__excepthook__ backup of original excepthook function sys.tracebacklimit int" (r ) maximum levels of traceback printed% <54
, #r C:one9:one9:oneD if no runnin" e.ception. 3tandard &odule traceback ha tool to proce and for&at the e infor&ation .
T'(e1-s Cla threading.Thread i u ed to create ne0 e.ecution path in current proce . 6t &u t (e called 0ith key0ord ar"u&ent . 3pecify thread code 0ith a calla(le target para& or (y o%erridin" run ðod Cre&e&(er callin" inherited __init__ in u(cla e D9 "i%e ar"u&ent in args and k args Ctuple and dictD9 "i%e a name to identify the thread - group currently not u ed C:oneD. th = threading.Thread(group,target,name,args,k args) th.start() start thread activit! (in another thread) th.run() thread code to execute 1 call target if not overriden th.join([timeout]) ait for th termination or timeout elapsed (float_dela!%
default to +one for infinite) th.getName() str" thread associated name th.setName(name) set thread associated name (initial name set b! class) th.isAlive() bool" test thread alive (started and run() not terminated) th.isDaemon() bool" test thread have daemon flag th.setDaemon(daemonic) set thread daemon flag 1 must be called before start3 Jnitial flag inherited from creating thread3 .!thon process exit onl! after last non1daemon thread3
Se&1p'"(es Cla e threading.Semaphore and threading.BoundedSemaphore pro%ide i&ple e&aphore for re ource countin" C0ithout70ith counter checkin"D. sem = threading.Semaphore([value5#]) semaphore ith initial counter sem = threading.BoundedSemaphore([value]) sem.acquire([blocking]) bool,None" ac0uire the semaphore (consume one
resource)3 blocking unspecified " ait R return +one S blocking true " return True S blocking false " don)t ait (tr!) R return True,False sem.release() release the semaphore (free one resource) ait R
C"n-! !"n V1(!1/#es Cla threading.Condition allo0 thread to hare tate CdataD protected %ia a Lock. 6&portant $ condition %aria(le ClockD must (e ac?uired 0hen callin" wait9 notify or notifyAll. 3ee Python doc . cond = threading.Condition([lock]) build ne condition variable% use user providen lock (Lock or RLock) else build a ne RLock cond.acquire(*args) value" ac0uire cond3 var3 lock% return lock3ac0uire()
value cond.release() release cond3 var3 lock cond.wait([timeout]) ait until notified or timeout elapsed1 timeout is a float_dela! (default to +one5infinite blocking)3 Telease cond3 var3 lock and ait for a notification,timeout then re1ac0uire lock3 cond.notify() ake up one aiting thread (if an!)3 cond.notifyAll() ake up all aiting threads3
4 thread canPt (e killed or pau ed e.ternally (y another thread. )hrea Local Stora&e Cla threading.local attri(ute %alue are thread local. 3u(cla it or u e it a a na&e pace. tlsdata = threading.local() tlsdata.x = 1 0elaye Start )hrea Cla threading.Timer i a u(cla of Thread 0hich effecti%ely run after a pecified inter%al fro& it tart. t = threading.Timer(interval,function,args=[],k args={}) t.cancel() timer ill never run 1 must not be alread! running Create a ti&er that 0ill run function 0ith ar"u&ent ar" and key0ord ar"u&ent k0ar" 9 after inter%al econd ha%e pa ed.
exceptions
for none
ENCODING - DECODING
3ee al o =nicode trin" Cp5D9 3ource encodin" Cp>D9 3tandard &odule codecs pro%ide (a e upport for encodin" 7 decodin" data. 2hi i u ed for character encodin" 9 (ut al o for data co&pre ion C@ip9 (@2D or data repre entation Cuu9 he.D. 3ee function 9 cla e and con tant for file encodin" in *ncoded -ile Cp,2D. ;odule encodings.aliases.
T;READS ) SYNC;RONI>ATION
Python thread u e nati%e thread . 4 "lo(al &ute. Cthe I6LD lock interpreter data durin" Python %irtual in truction e.ecution Cit i unlocked durin" 67# or lon" co&putation in nati%e codeD. Check for thread 0itchin" and i"nal proce in" i perfor&ed at re"ular inter%al. sys.getcheckinterval() int" current thread s itching check interval# sys.setcheckinterval(interval) se thread s itching check interval#
,
Mu u1# E2c#us!"n Cla e threading.Lock and threading.RLock pro%ide &utual e.clu ion (et0een thread . Lock doe nPt allo0 a thread to re-ac?uire a lock it already o0n 9 RLock doe Creentrant-lockD. lock = threading.Lock() lock = threading.RLock() lock.acquire([blocking]) bool,None" ac0uire the lock3 blocking unspecified " ait R return +one S blocking true " ait R return True S blocking false " don)t ait (tr!) R return True,False lock.release() unlock a previousl! ac0uired lock
;u t relea e a lock a&e ti&e a it 0a ac?uired. Iood practice to acquire7release lock in try7finally (lock . -or porta(le inter-proce &ute.9 ee third party glock.py &odule.
Sync'("n!7e- 8ueues ;odule Queue pro%ide a cla Queue to tore data in a ynchroni@ed -6-# ?ueue9 and t0o e.ception cla e Full and Empty. 6n (lockin" &ode9 full ?ueue (lock producer and e&pty ?ueue (lock con u&er Cin non-(lockin" &ode they rai e e.ception D. #ther or"ani@ation can (e (uilt 0ith u(cla in" C ee ource for internal ðod D. 0 = queue.Queue(maxsi/e) build ne 0ueue 1 infinite 0ueue if maxsi/e<54 0.qsize() int" si/e of the 0ueue 1 at call time 0.empty() bool" test if 0ueue si/e if 4 1 at call time 0.full() bool" test if 0ueue si/e is maxsi/e 1 at call time 0.put(item[,block[,timeout]]) put in 0ueue 1 block can be true,false% -imeout can be None,float_dela!3 2a! raise Queue.Full exception3 0.put_nowait(item) same as put(item%False) 0.get([block[,timeout]]) item" removed from 0ueue 1 block can be true,false% -imeout can be None,float_dela! 1 ma! raise Queue.Empty exception 0.get_nowait() same as get(False)
PROCESS
Cu((en P("cess 3tandard &odule os ha tool to "et infor&ation a(out and &anipulate current proce and it en%iron&ent.
"#itin& :or&ally Python proce e.it 0hen there i no &ore non-dae&on thread runnin". sys.exit([arg54]) exit via a SystemExit exception (ma! be catch) 1 arg is
exit code
*.pre
T'(e1-!n% Func !"ns = e tandard hi"h le%el &odule threading 0hich pro%ide e%eral cla e $ Thread9 local Cfor thread local tora"eD9 Event9 Lock and RLock C&ute. D9 Semaphore and BoudedSemaphore9 Timer. ;odule threading al o pro%ide function $
13a
E3en s Cla threading.Event i a ynchroni ation fla" 0ith thread (lockin" &echani & to 0ait for the fla". evt = threading.Event() ne event% ith internal flag set to Aalse
13b
os._exit(n) exit ithout cleanup os.abort() exit via a IJH>CT- signal (signal ma! be handled) -ollo0in" e.it code are defined in os C=ni.D $ no error EX_OK 13c
EX_USAGE EX_DATAERR EX_NOINPUT EX_NOUSER EX_NOHOST EX_UNAVAILABLE EX_SOFTWARE EX_OSERR EX_OSFILE EX_CANTCREAT EX_IOERR EX_TEMPFAIL EX_PROTOCOL EX_NOPERM EX_CONFIG EX_NOTFOUND
command used incorrectl! incorrect input data unavailable,inaccessible input unkno n user unkno n host re0uired service unavailable internal error DI error missing,inaccessible file can)t create output error during file J,D temporar! failure illegal,invalid,not understood protocol exchange not enough permissions (out of file perms) configuration problem missing data
getpgrp() int" current gid (=nix) getgroups() [int]" list of supplemental associated gid (=nix) setgroups(groups) set list of supplemental associated gid (=nix) setpgrp() call s!stem function# (=nix) getppid() int" parent)s pid (=nix) setsid() call s!stem function# (=nix) getpgid(pid) int" process group id of process id pid (45current) (=nix) getsid(pid) call s!stem function# (=nix) setpgid(pid,pgrp) set process pid group to pgrp# (=nix)
,
SIG_IGN 1" ignore signal handler function NSIG int" highest signal number 7# ;odule al o define i"nal nu&(er CPo i. e.a&ple - runti&e definition i platfor& dependantD $ SIGHUP terminal or control processus disconnection SIGINT ke!board interrupt SIGQUIT 0uit re0uest from ke!board SIGILL illegal instruction SIGABRT abort stop signal SIGFPE floating point error SIGKILL the MJEE signal SIGSEGV invalid memor! reference SIGPIPE pipe rite ithout reader SIGALRM alarm timer elapsed SIGTERM termination signal SIGUSR1 user signal # SIGUSR2 user signal $ SIGCHLD terminated,stopped child SIGCONT continue process (if stopped) SIGSTOP stop process SIGTSTP stop re0uest from ke!board SIGTTIN read on tt! hile in background SIGTTOU rite on tt! hile in background ee your platfor& docu&entation Cman # $i%na& on Linu.D. -unction to end i"nal are in os &odule $ kill(pid,sig) kill process pid ith signal sig (=nix) killpg(pgid,sig) kill process group pgid ith signal sig (=nix)
times() (ut% st% cut% cst% ert)" float_dela!" user time% s!stem time% children)s
user time% children)s s!stem time% elapsed real time>
niceness (=nix)
Jou can in tall e.it function Cfor nor&al e.itD 0ith &odule atexit. registerCfunc[9Targs[9TTkargs))D register function to be called ith args and Re"i tered function are called in re%er e order of re"i tration. 1ypa ed 0hen proce i ter&inated (y a i"nal9 an internal error9 or an os._exit. "n%ironment 5ariables environ <dict" environment variables 1 modification call putenv if getenv(varname[,default5+one]) str" environment variable value putenv(varname,value) set environment variable 1 affect later started
subprocess 1 ma! cause memor! leaks (see platform documentation) supported> kargs
Host Informations strerror(code) str" error message for the error code uname() tuple" current operating s!stem identification% (s!sname% nodename%
release% version% machine) (recent =nix)
sys.byteorder str" host native b!te order big or little sys.winver str" version number for registr! ke!s (Oindo s) sys.platform str" platform identifier (ex3 linux2) -ollo0in" data are in os and in os.path. defpath str" search path for os.exec*p*() and os.spawn*p*() if linesep str" end of line char(s) for the plaftorm devnull str" file path of null device !ython Informations sys.builtin_module_names (str)" names of modules compiled into sys.copyright str" cop!right of interpreter sys.hexversion int" .!thon version ith one digit b! b!te sys.version str" interpreter version 7 build 7 compiler sys.dllhandle int" handle of .!thon NEE (Oindo s) sys.executable str" name of interpreter executable binar! sys.prefix str" director! prefix for platform independant .!thon files sys.api_version int" version of .!thon * >.J sys.version_info (int{&},str,int)" (major% minor% micro% releaselevel% serial) 1 release in alpha% beta% candidate% final
interpreter environment .>-L not defined
3o&e function al o in os.path $ expanduser(path) str" path ith initial UVU or UVuserU replaced expandvars(string) str" string ith $name or ${name} environment
variable replaced
0irectory6 +iles6 )erminal 3ee al o Con ole 5 6nteracti%e 6nput7#utput Cp2D9 and -ile - 2er&inal #peration Cp,,D. chdir(path) change current orking director! to path fchdir(fd) change current orking director! to thus represented b! file
descriptor
S!&p#e E2 e(n1# P("cess C"n ("# = e tandard &odule subprocess. 6t 0rap e.ternal proce creation and control in Popen o(8ect . Child proce e.ception rai ed (efore e.ecution are re-rai ed in parent proce 9 e.ception 0ill ha%e child_traceback attri(ute C trin"D. :ote $ subprocess tool 0ill ne%er call 7(in7 h i&plicitly.
PIPE -1" constant value used for Popen stdin stdout stderr params call(*args,**k args) int" run command ith arguments% ait for completion% return retcode 1 convenient rapper around Popen object = e Popen o(8ect a proce control tool $ p = Popen(args,bufsi/e54,executable5+one,stdin5+one,stdout5+one, stderr5+one,preexec_fn5+one,close_fds5Aalse,shell5Aalse,c d5+one, env5+one,universal_ne lines5Aalse,startupinfo5+one,creationflags54D args i a trin"7li t of trin" ['comman(','ar%1','ar%)',] bufsi/e like for file7open function executable can (e u ed to pro%ide co&&and in place of ar%$[*] stdin9 stdout and stderr can (e PIPE to capture file and co&&unicate 0ith u(proce preexec_fn i called 8u t (efore child proce e.ecution close_fds (ool force u(proce inherited file to (e clo ed9 e.cept 0 , and 2 shell (ool force e.ecution of co&&and throu"ht the hell c d trin" pecify 0orkin" directory to et for u(proce tart env dictionnary pecify en%iron&ent %aria(le for u(proce universal_ne lines tran late all ne0line to \n Clike U &ode for file D startupinfo and creationflags are optional infor&ation for proce creation under Findo0 p.poll() int,None" check child process termination% return returncode
attribute p.wait() int" ait for child process to terminate% return returncode attribute> p.communicate(input5+one) (stdout,stderr)" send data (input string)to
getcwd() str" current orking director! getcwdu() unicode" current orking director! chroot(path) change process file1s!stem root to path (=nix) umask(mask) int" set current numeric umask and return previous one ctermid() str" filename of controlling terminal (=nix) getlogin() str" name of user logged on controlling terminal (=nix) .ser6 process6 &roup I0s id9 gid$ "roup id9 uid$ u er id getpid() int" current pid getegid() int" effective gid (=nix) setegid(egid) set process effective gid (=nix) geteuid() int" effective uid (=nix) seteuid(euid) set process effective uid (=nix) getgid() int" real gid (=nix) setgid(gid) set process gid (=nix) getuid() int" current process) uid (=nix) setuid(uid) set process current uid (=nix) setregid(rgid,egid) set process real and effective gid (=nix) setreuid(ruid,euid) set process real and effective uid (=nix) 14a
pid$ proce
S!%n1# ;1n-#!n% 3tandard &odule signal. 3ee doc for "eneral rule a(out i"nal u a"e in Python. 3i"nal handler are calla(le f(signalnum,stackframe).
alarm(time) float_dela!" previous alarm remaining time 1 re0uest a ne
IJH>ET2 in time seconds 1 cancel previous one 1 time4 (=nix)
alarm(0) float_dela!" previous alarm remaining time 1 cancel previous alarm getsignal(signalnum) fct" current signal handler or IJH_JH+ or IJH_NAE or
+one (handler not installed from .!thon) (=nix)
pause() sleep process until a signal is received (=nix) signal(signalnum,handler) fct" previous handler for signal (as getsignal)
1 install ne thread handler (ma!be IJH_JH+ or IJH_NAE too) 1 onl! callable in main
-ollo0in" i"nal con tant are defined $ SIG_DFL 0" default signal handler function 14b
14c
stdin% read data from stdout,stderr until end1of1file% ait process to terminate% return read values 1 data read is buffered in memor! p.stdin file,None" standard input from chil process if captured p.stdout file,None" standard output from chil process if captured p.stderr file,None" error output from chil process if captured p.pid int" process JN of child process p.returncode int,None" child process return code (+one if not terminated) 1 on =nix 1+ for subprocess terminated b! signal +
WIFSIGNALED(status) bool" test exited on signal (=nix) WIFEXITED(status) bool" test process exited via exit($) s!stem call (=nix) WEXITSTATUS(status) int" if exited via exit($)% return exit parameter (=nix) WSTOPSIG(status) int" signal having stopped process (=nix) WTERMSIG(status) int" signal having exited process (=nix) !ipes On !rocess 2hree function a%aila(le in popen2 &odule Cand in os &odule 0here tdin7 tdout return %alue are in%ertedD. popen2(cmd[,bufsi/e[,mode]]) (file{$})" (stdout%stdin)" execute cmd as popen3(cmd[,bufsi/e[,mode]]) (file{&})" (stdout%stdin%stderr)" execute cmd
as sub1process popen4(cmd[,bufsi/e[,mode]]) (file{$})" stdout_stderr%stdin)" execute cmd as sub1process Fhere bufsi/e i (uffer i@e for 67# pipe 9 and mode i 'b' C(inary trea& D or 't' Cte.t trea& 9 defaultD. Para& cmd i a trin" pa ed sub1process
p.setFeature(featurename,value) set feature to value p.getProperty(propert!name) current settings for propert!$ p.setProperty(propert!name,value) set propert! to value
2here i al o an IncrementalParser u(cla interface 0ith $ p.feed(data) process a chunk of data p.close() assume end of document% check ell1formedness% cleanup p.reset() after close% prepare ne parsing
, 2
= e subprocess &odule 0hen po i(le Ccleaner9 i&pler interface9 ee doc for e.a&ple D. 3ee al o e.ternal &odule pexpect.
-eature na&e in xml.sax.handler a feature_xxx. Property na&e in xml.sax.handler a property_xxx. InputSource Interface
A-31nce- E2 e(n1# P("cess C"n ("# 3ee follo0in" function fro& os &odule. execl(path,[arg[,]]) execle(path,[arg[,]],env) execlp(file,[arg[,]]) execlpe(file,[arg[,]],env) execv(path,args) execve(path,args,env) execvp(file,args) execvpe(file,args,env) Fith exec ne0 pro"ra& replace current proce Cfct donPt returnD. PpP %er ion u e P42G to locate e.ecuta(le file. PeP %er ion u e a dict env to etup ne0 pro"ra& en%iron&ent. PlP %er ion u e a po itioned arg9 PvP %er ion u e li t of %aria(le args. spawnl(mode,path,[arg[,]]) int spawnle(mode,path,[arg[,]],env) int spawnlp(mode,file,[arg[,]]) int spawnlpe(mode,file,[arg[,]],env) int spawnv(mode,path,args) int spawnve(mode,path,args,env) int spawnvp(mode,file,args) int spawnvpe(mode,file,args,env) int Fith spawn new process is created. 0lpev0 versions li%e for exec. 6f mode i P_NOWAIT or P_NOWAIT09 return child pid C=ni.D or proce handle CFindo0 D. 6f mode i P_WAIT9 0ait child ter&ination and return it e.it code C!0D or it killin" i"nal C<0D. #n Findo0 &ode can (e9 P_DETACH C a&e a P_NOWAIT (ut ne0 proce detached fro& callin" proce con oleD or P_OVERLAY Ccurrent proce i replacedD. fork() pid" fork a child process% return 4 in child% child pid in parent (=nix) forkpty() (int{$})" (pid%fd)" fork using ne pseudo1terminal for child 1 pid
is 4 in child% child pid in parent 1 fd pseudo1terminal master end (=nix) startfile(path) open file path as if double1clicked in explorer (Oindo s)
to os.system - on =ni. it can (e a e?uence of trin" pa directly to the pro"ra& 0ithout hell inter%ention.
ed
Pro%ide ource of data for par er. isrc.setPublicId(id) set public identifier isrc.getPublicId() unicode" public identifier isrc.setSystemId(id) set s!stem identifier isrc.getSystemId() unicode" s!stem identifier isrc.setEncoding(encoding) set encoding 1 must be a string acceptable
for an W2E encoding declaration 1 ignored if JnputIource contains character stream isrc.getEncoding() str,None (if unkno n) isrc.setByteStream(b!tefile) set input b!te stream 1 ignored if JnputIource contains character stream isrc.getByteStream() b!te stream isrc.setCharacterStream(charfile) set character (=nicode) stream isrc.getCharacterStream() character stream
#n =ni.9 popen2 &odule al o define Popen3 cla Cu ed in popen2 and popen3 function D and Popen4 cla Cu ed in popen4 functionD $ Popen3(cmd[,capturestderr[,bufsi/e]]) Popen3" cmd5shell command%
captudestderr5bool (default Aalse) Popen4(cmd[,bufsi/e]) Popen4
Popen> and Popen4 o(8ect ha%e follo0in" attri(ute $ p.poll() int" child return code or 1# if child not terminated p.wait() int" child return code p.fromchild file" output from child (stdout and stderr for Popen4) p.tochild file" input to child p.childerr file" error output from child if re0uested else +one (+one for Popen4) p.pid int" child process pid 3ee al o &odule commands C=ni.D.
Locator Interface 6n tance of Locator pro%ide the e ðod $ loc.getColumnNumber() int" column number here current event ends loc.getLineNumber() int" line number here current event ends loc.getPublicId() str" public identifier of current event loc.getSystemId() str" s!stem identifier of current event Attributes Interface 4l o i&ple&ent part &appin" protocol Ccopy()9 get()9 has_key()9 items()9 keys()9 and values()D. ai.getLength() int" number of attributes ai.getNames() [unicode]" names of attributes ai.getType(name) t!pe of attribute name 1 normall! 'CDATA' ai.getValue(name) unicode" value of attribute name Attributes-S Interface 4l o i&ple&ent Attributes interface. ansi.getValueByQName(name) unicode" value of attribute 0ualified name ansi.getNameByQName(name) (unicode{$})" (namespace% localname) for
0ualified name ansi.getQNameByName(namepair) unicode" 0ualified name for (namespace% localname) ansi.getQNames() [unicode]: 0ualified names of all attributes
XML PROCESSING
3e%eral &odule to proce H;L are a%aila(le. 3o&e 0ith tandard 34H and <#; interface 9 other 0ith &ore Pythonic interface . 3ee al o third party PyXML e.ten ion packa"e.
SAX - E3en --(!3en 1a e function in xml.sax &odule. make_parser([parser_list]) XMLReader" built from first parser available parse(filename_or_stream,content_handler[,error_handler]) parse
document using first parser available
wait() (int{$})" (pid%status) ait completion of a child process (=nix) 1 status50xZZTT here ZZ5exit code% TT5signal num waitpid(pid,options) (int{$})" (pid%status) (=nix)"
pid>4 ait for specific process% pid54 ait for an! child in process group% pid51# ait for an! child of current process% pid<1# ait for an! process in process group 1pid option in WNOHANG% WCONTINUED% WUNTRACED status50xZZTT here ZZ5exit code% TT5signal num
7ML,ea er Interface <efined in xml.sax.xmlreader. p = xml.sax.make_parser() XMLReader object p.parse(source) completl! parse source 1 source is filename or =TE or file1
like or JnputIource1 input b!te streams (not character streams) p.getContentHandler() ContentHandler" current one p.setContentHandler(handler) set current content handler p.getDTDHandler() DTDHandler" current one p.setDTDHandler(handler) set current N-N handler p.getEntityResolver() EntityResolver" current one p.setEntityResolver(handler) set current entit! resolver p.getErrorHandler() ErrorHandler" current one p.setErrorHandler(handler) set current error handler p.setLocale(locale) set locale for errors and arnings p.getFeature(featurename) current settings for feature#
ContentHan ler Interface <efined in xml.sax.handler. 6t ðod are handler called 0hen par er find H;L tructure . ch = MyContentHandler() ContentHandler subclass object ch.setDocumentLocatorClocatorD set locator for origin of document events ch.startDocument() beginning of document ch.endDocument() beginning of document ch.startPrefixMapping(prefix,uri) begin of a prefix1=TJ namespace
mapping 1 see doc ch.endPrefixMapping(prefix) end of a prefix1=TJ namespace mapping ch.startElementCname,attrsD start of an element 1 non1namespace mode 1 attrs has an Attributes interface (ma! be reused 1 cop! data)
waitpid(pid,options) (int{$})" (pid%status) (Oindo s)" pid is an! process handle (>4) 1 option ignored 1 status50xZZ00 here ZZ5exit code Status informations e#traction WCOREDUMP(status) bool" test process generated core1dump (=nix) WIFCONTINUED(status) bool" test process continued from a job control stop WIFSTOPPED(status) bool" test process stopped (=nix) 15a
(=nix)
15b
15c
ch.endElement(name) end of an element 1 non1namespace mode ch.startElementNS(name,0name,attrs) start of an element 1 namespace mode 1 name is (uri%localname) 1 0name is ra W2E name 1 attrs has an AttributesNS interface (ma! be reused 1 cop! data) 1 0name ma! be None (upon feature_namespace_prefixes) ch.endElementNS(name,0name) end of an element 1 namespace mode ch.characters(content) character data 1 content is str or =nicode ch.ignorableWhitespace( hitespace) hitespaces ch.processingInstruction(target,data) processing instruction ch.skippedEntity(name) entit! not processed
+eatures 1 !roperties <efined in xml.sax.handler. <ont "i%e their %alue9 (ut their &eanin". feature_namespaces $ True perform namespace processing3 False no
,
o.hasChildNodes() bool" test an! subnode existence o.isSameNode(other) bool" test other refers same node o.appendChild(ne *hild) ne subnodes 1 return ne child *hild" add ne child node at end of
namespace processing (so no namespace prefixes)3 feature_namespace_prefixes $ , True report original prefixed names and attributes used for namespace declarations3 feature_string_interning $ , True intern all names (elements% prefixes% attributes% namespace =TJs% local names)3 feature_validation $ , True report all validation errors3
o.insertBefore(ne *hild,ref*hild) ne *hild" add ne child node before an existing subnode 1 at end of subnodes if ref*hild is +one 1 return ne child o.removeChild(old*hild) old *hild" remove a subnode% return it 1 hen no o.replaceChild(ne *hild,old*hild) replace existing subnode one o.normalize() join adjacent text nodes longer used% must call old*hild.unlink() ith a ne
0)0Han ler Interface <efined in xml.sax.handler. 6t ðod are handler called 0hen par er need <2< relati%e 0ork. dh = MyDTDHandler() DTDHandler subclass object dh.notationDecl(name9publicJd,s!stemJd) notation declaration dh.unparsedEntityDecl(name,publicJd,s!stemJd,ndata) unparsed
entit! declaration
feature_external_ges $ , True include all external general (text) entities3 feature_external_pes $ , True iJnclude all external parameter entities% all_features list of all features property_lexical_handler $ optional extension handler for lexical events
(like comments)3 including the external N-N subset3
-o eList 4 e?uence of node 9 u a(le a a Python e?uence C&ay(e &odifia(le upon i&ple&entationD. o.length int" number of nodes in the se0uence o.item(i) Node,None" ith item in the list 0ocument)ype 3u(cla of Node. o.nodeType DOCUMENT_TYPE_NODE o.publicId unicode,None$ public identifier for external subset of N-N> o.systemId unicode,None$ s!stem identifier =TJ for external subset of
N-N o.internalSubset unicode,None$ complete internal subset from the document 1 ithout brackets o.name unicode,None$ name of root element (as given in ND*-K.F) o.entities NamedNodeMap,None$ definition of external entities o.notations NamedNodeMap,None$ definition of notations
property_declaration_handler $ optional extension handler for N-N1 property_dom_node $ , visited ND2 node (if ND2 iterator)
root ND2 node3 propert!)3
,
"ntity,esol%er Interface <efined in xml.sax.handler. 6t ðod are handler called 0hen par er need e.ternal entity re olution. er = MyEntityResolver() EntityResolver interface object er.resolveEntity(publicJd,s!stemJd) str,InputSource" default return
s!stemJd
property_xml_string $ literal string source of current event (read onl! all_properties list of all properties names can only (e read durin" par in" Cand &odified (eforeD.
"#ceptions <efined in xml.sax &odule. SAXException(msg[,exception]) SAXParseException(msg,exception,locator) , invalid 123 SAXNotRecognizedException(msg[,exception]) SAXNotSupportedException(msg[,exception]) "rrorHan ler Interface <efined in xml.sax.handler. 6t ðod are handler called 0hen par er detect an error. 2heir exception para&eter "et SAXParseException o(8ect . eh = MyErroHandler() ErrorHandler interface object eh.error(exception) recovererable error 1 parsing ill continue if method
return eh.fatalError(exception) unrecoverable error 1 parsing must stop eh.warning(exception) minor return arning 1 parsing ill continue if method
DOM - In-&e&"(y T(ee <efined in xml.dom. 20o function to re"i ter7acce <#; proce or 9 and o&e con tant . registerDOMImplementation(name,factor!) register ND2
getDOMImplementation([name[,features]]D ND2 implementation 1 name ma! be None 1 ma! found name in env3 var PYTHON_DOM 1 features is
((featurename%version)%6 EMPTY_NAMESPACE no namespace associated ith a node implementation factor!
0ocument 3u(cla of Node. o.nodeType DOCUMENT_NODE o.documentElement Element$ root element of the document o.createElement(tag+ame) Element$ ne # element node> o.createElementNS(namespace=TJ,tag+ame) Element$ ne
o.createComment(data) Element$ ne
XML_NAMESPACE xml prefix namespace XMLNS_NAMESPACE namespace =TJ for namespace declarations 1 ND2 level $
specification definition
# element node ith namespace 1 tag+ame ma! have prefix o.createTextNode(data) Element$ ne # text node containing data #
-o e <efined in xml.dom9 cla Node i parent of H;L co&ponent node cla e . o.nodeType int" (ro) in ELEMENT_NODE% ATTRIBUTE_NODE% TEXT_NODE% CDATA_SECTION_NODE% ENTITY_NODE% PROCESSING_INSTRUCTION_NODE% COMMENT_NODE% DOCUMENT_NODE% DOCUMENT_TYPE_NODE% NOTATION_NODE o.parentNode Node,None" (ro) 1 +one for >ttr nodes o.attributes NamedNodeMap,None" attribute objects for elements% else
+one o.previousSibling Node,None" (ro) previous node in parent)s children o.nextSibling Node,None" (ro) next node in parent)s children o.childNodes [Node]" (ro) list of subnodes o.firstChild Node,None" (ro) first subnode o.lastChild Node,None" (ro) last subnode o.localName unicode,None" (ro) element name ithout namespace prefix o.prefix unicode,None" (ro) element namespace prefix 1 ma! be empt! string or +one o.namespaceURI unicode,None" (ro) =TJ associated to element namespace o.nodeName unicode,None" (ro) usage specified in subclasses o.nodeValue unicode,None" (ro) usage specified in subclasses o.hasAttributes() bool" test an! attribute existence
SA7 .tilities <efined in xml.sax.saxutils. escape(data[,entities]) str" & < > escaped 1 escape other entities replacing
mapping strings (ke!s) b! corresponding identifiers
o.createProcessingInstruction(target,data) Element$ ne processing instruction node containing target and data o.createAttribute(name) Element$ ne # attribute node
unescape(data[,entities]) str" & < > unescaped 1 unescape quoteattr(data[,entities]) str" as escape() 7 0uote string to be used as
attribute value other entities replacing mapping identifiers (ke!s) b! corresponding strings
o.createAttributeNS(namespace=TJ,0ualified+ame) Element$ ne # attribute node ith namespace1 tag+ame ma! have prefix> o.getElementsByTagName(tag+ame) NodeList$ search for all descendants (deep search) having t!pe name o.getElementsByTagNameNS(na&e pace=R6,local+ame) NodeList$ search for all descendants (deep search) having namespace =TJ and local name (part after prefix)
,
:e0 node are tandalone - you &u t in ert7a docu&ent part . "lement 3u(cla of Node. o.nodeType ELEMENT_NODE o.tagName unicode" element t!pe name 1
Cla XMLGenerator i a ContentHandler 0ritin" 34H e%ent into an H;L docu&ent Cie. reproduce ori"inal docu&entD. XMLGenerator([out[,encoding]]) content handler" out file1like% deault to s!s3stdout 1 encoding default to 'iso-8859-1' Cla XMLFilterBase i a default pa -throu"ht e%ent 9 can (e u(cla ed to &odify e%ent on-fly (efore their proce in" (y application handler . XMLFilterBase(base) events filter
ith namespace ma! contain colons o.getElementsByTagName(tag+ame) NodeList$ search for all descendants (deep search) having t!pe name o.getElementsByTagNameNS(namespace=TJ,local+ame) NodeList$ search for all descendants (deep search) having namespace =TJ and local name (part after prefix) o.getAttribute(attname) unicode" attribute value
16a
16b
16c
o.getAttributeNode(attrname) Attr" attribute node o.getAttributeNSCnamespace=TJ,local+ame) unicode" attribute value o.getAttributeNodeNS(namespace=TJ,local+ame) Attr" attribute node o.removeAttribute(attname) remove attribute b! name 1 ignore missing attribute o.removeAttributeNode(old>ttr) Attr" remove and return old >ttr o.removeAttributeNS(namespace=TJ,local+ame) remove attribute b! namespace =TJ and name 1 ignore missing attribute o.setAttribute(attname,value) set attribute string value o.setAttributeNode(ne >ttr) Attr" set attribute from a ne Attr node 1 return old one o.setAttributeNodeNS(ne >ttr) Attr" set attribute from a ne Attr node ith namespace =TJ and local name 1 return old one o.setAttributeNS(namespace=TJ,0name,value) Attr" set attribute string value from a namespace =TJ and 0name ( hole attribute name) 1 return old one
"#ception
value
pa!ams
e'ample
Que tion &ark tyle, FG*R* na&eK[ 'qmark' :u&eric9 po itional tyle, or 2 FG*R* na&eK$, 'numeric' :a&ed tyle2 FG*R* na&eK$na&e 'named' 4:36 C printf for&at code , FG*R* na&eKZ 'format' Python e.tended for&at code 2 FG*R* na&eKZCna&eD 'pyformat , Para&eter a po itional %alue in a e?uence. 2 Para&eter a na&ed %alue in a &ap.
"#ceptions CStandardErrorD Warning , i&portant 0arnin" Error , a catch all InterfaceError , pro(le& 0ith interface Cnot data(a eD DatabaseError DataError , pro(le& 0ith data proce in" OperationalError , pro(le& durin" data(a e operation IntegrityError InternalError ProgrammingError , 3QL pro"ra&&in" related error NotSupportedError *.ception cla e &ay al o (e a%aila(le a Connection o(8ect attri(ute CoptionalD. Connection connect(dsn[,user[,pass ord[,host[,database]]]]) Connection object
(interface defined as a guideline) 1 dsn5data source name string> cx.errorhandler fct" (optional) handler for connection errors 1 errorhandler(connection% cursor,+one% errorclass% errorvalue) 1 default handler fill cx3messages and ma! raise exceptions cx.messages [(exception class,exception value)]" (optional) messages received from database for operations ith connection cx.close() terminate connection (ma! rollback if not commited) cx.commit() commit pending transactions cx.rollback() rollback pending transactions (optionnal) cx.cursor() ne
exception.code int" ND2 code corresponding to exception exception.msg string" message for exception
Attr 3u(cla of Node. o.nodeType ATTRIBUTE_NODE o.name unicode" (ro) attribute full name 1 ma! have colons o.localName unicode" (ro) attribute name 1 part after colons o.prefix unicode" (ro) attribute prefix 1 part before colons 1 ma! be empt! -ame -o eMap 4 &appin" of node - e.peri&entally u a(le a a Python &appin". o.length int" length of attributes list o.item(index) Attr" attribute at index 1 arbitrar! but consistent order Comment 3u(cla of Node. Cannot ha%e u(node. o.nodeType COMMENT_NODE o.data unicode" content of the comment% )e#t 3u(cla e of Node. Cannot ha%e u(node. 2e.t part in an ele&ent. o.nodeType TEXT_NODE o.data unicode" text content C0A)ASection 3u(cla e of Node. Cannot ha%e u(node. C<424 ection in a docu&ent9 &ay ha%e &ultiple C<4243ection node for one C<424. o.nodeType CDATA_SECTION_NODE o.data unicode" *N>-> content !rocessin&Instruction 3u(cla e of Node. Cannot ha%e u(node. Repre ent a proce in" in truction in the H;L docu&entM thi inherit fro& the :ode interface and cannot ha%e child node . o.nodeType PROCESSING_INSTRUCTION_NODE o.target unicode" (ro) processing instruction content up to first hitespace o.data unicode" (ro) processing instruction content after first hitespace "#ceptions Python &ap <#; error code to e.ception .
<#; code con tant "#ception
DOMException DomstringSizeErr , implementation limit reach HierarchyRequestErr , insert at wrong place IndexSizeErr , inde. range error InuseAttributeErr , Attr node already used in tree InvalidAccessErr , param/operation unsupported by ob4ect InvalidCharacterErr , character invalid in the conte.t InvalidModificationErr , can0t modify node type InvalidStateErr , try to use an undefined/unusable ob4ect NamespaceErr , change forbidden in namespace conte.t NotFoundErr , node don0t e.ist in referenced conte.t NotSupportedErr , operation/type unsupported by implementation NoDataAllowedErr , no data for this node NoModificationAllowedErr , can0t modify ob4ect SyntaxErr , invalide/illegal string WrongDocumentErr , impl. can0t migrate nodes between docs
DATABASES
ithout <!-- and -->
3ee Python.or" 0iki for a li t of data(a e interface &odule . 3o&e interface are for e.ternal <1 en"ine C;y3QL9 Po t"re3QL9 1erkeley<19 3QLite9 ;etakitD9 other for pure Python <1 en"ine C"adfly9 L#<19 /irky1a e9 1u@hu"D.
Gene(!c 1ccess " DBM-s y#e DBs 3tandard &odule anydbm i a front-end to o&e a%aila(le <1 &odule $ dbhash Cbsddb1erkeley <1D9 gdbm CI:= d(&D9 dbm Cuni. d(&D and the lo0 porta(le fall(ack dumbdbm. <ata tored in <1;- tyle file are acce ed %ia a dictionary-like interface 0here key and %alue &u t (e str. open(filename[,flag[,mode]]) dictionar!1like object" flag in 'r' (read1 default)% 'w' ( rite)% 'c' (create if doesn)t exist)% )n' (create ne empt!) 1
mode is unix mode flags for creation errortuple of exception classes from NC modules (an!dbm3error%)
Cursor object
Cursor
cu.arraysize int" (TO) number of ro s to fetch ith fetchmany 1 default to # cu.connection Connection" (optional) connection used b! cursor cu.description [(name, t!pe_code, displa!_si/e, internal_si/e, precision, scale, null_ok)],None" describe result columns cu.errorhandler fct" (optional) handler for connection errors 1 errorhandler(connection% cursor% errorclass% errorvalue) 1 default handler fill cx3messages and ma! raise exceptions 1 inherited from connection cu.lastrowid int,None" (optional) ro id of last modified column cu.messages [(exception class,exception value)]" (optional) messages received from database for operations ith cursor cu.rowcount int" number of ro s produced,affected b! last re0uest 1 1#or +one if re0uest cant touch ro s cu.rownumber int,None" (optional) 41based index of the cursor in the result set if available cu.callproc(procname[,parameters]) (parameters) 1 (optional) call db stored procedure 1 in result out and inout parameters ma! have been replaced b! procedure cu.close() close the cursor cu.execute(oper[,params]) prepare and execute NC re0uest 1 params# is a se0uence or a mapping (see module paramstyle variable)
= e &odule whichdb to identify ri"ht <1 &odule for e.i tin" file. -or ne0 file 9 u e fir t a%aila(le <1 &odule in the order of the li t. 2hi i u ed (y shelve &odule C ee Per i tence9 p,2D. <1 &odule can ha%e pecific function related to their (ackend9 ee doc .
S 1n-1(- DB API ."( S8L -1 1/1ses Ienerally &odule for 3QL data(a e u e the 3tandard Python <ata(a e 4P6 %2 Cdefined in P*P24ED.
A!I Informations apilevel str" currentl! )#34) or )$34) 1 )#34) if undefined threadsafety int" level of thread safet!
%
0 1 2 3
sha!e module no ye ye ye
sha!e #onne#tions no no ye ye
sha!e #u!so!s no no no ye
cu.executemany(oper,params_se0) like execute% ith a se0uence of params (for multiple values) cu.fetchone() (column_value,) , +one" next ro of 0uer! result% +one hen no more data available cu.fetchmany([si/e]) [(column_value)]" next set of ro s of 0uer! result% empt! list hen no more data available 1 si/e default to cu3arraysize
17c
cu.fetchall() [(column_value)]: all remaining ro s of 0uer! result% empt! list hen no more data available cu.next() (column_value) " (optional) next ro of 0uer! result% raises StopIteration hen no more data available
cu.nextset() True,None" (optional) discards results up to next available set cu.scroll(value[,mode=)relative)]) (optional) 1 scroll cursor in current result set 1 mode in 'relative'% 'absolute'3 cu.setinputsizes(si/es) predefine memor! areas for executeXXX operations parameters 1 si/es5(param_si/e%6 1 param_si/e5-!pe Dbject or int (max length of a string param) 1 param_si/e5+one for no predefinition cu.setoutputsize(si/e[,column]) set column buffer si/e for fetches of large columns (e3g3 ED+Hs% CEDCs% etc3) b! executeXXX 1 column is index in result 1 all columns if column not specified cu.__iter__() Cursor" (optional) object itself
;ethod __getitem__ i u ed to "et %alue in para& 9 u in" po ition or na&e. Can u e tuple or dict or your o0n cla o(8ect 0ith it __getitem__. 6f next and __iter__ are defined9 cur or are itera(le.
,
0' types Constructors Date(!ear,month,da!) object to hold a date value TimeChour,minute,second) object to hold a time value Timestamp(!ear,month,da!,hour,minute,second) object to hold a time
stamp value
DateFromTicks(ticks) object to hold a date value from a given ticks value TimeFromTicks(ticks) object to hold a time value from a given ticks value TimestampFromTicks(ticks) object to hold a time stamp value from a given Binary(string) object to hold a long binar! string value 3QL :=LL %alue repre ented (y Python None. 0' types )ypeco es STRING string1based column (*L>T) BINARY long binar! column (ED+H% T>O% CEDCs) NUMBER numeric column DATETIME date,time column ROWID ro JN column (*L>T)
ticks value
TOOLS
Pro%iden 0ith the nake $ Code (ench $ ee &odule timeit Cp,0D. 4 &u t ha%e $ pychecker9. 2ake a look $ pylint9 psyco9 pyrex9 pycount9 trace2html.
18a
18b
18c