You are on page 1of 17

Python 2.

4 Quick Reference Card


2005-2007 Laurent Pointal License CC [ y nc sa!

CARD CONTENT
"n#iron$ent %aria les............................ & Co$$and-line '(tions............................& )iles "*tensions.......................................& Lan+ua+e ,ey-ords................................ & .uiltins.................................................... & Types......................................................... 1 Functions................................................... 1 /tate$ents..............................................& Blocks........................................................ 1 Assignment Shortcuts................................1 Console 0 1nteracti#e 1n(ut2'ut(ut.........& ' 3ects4 5a$es and 5a$es(aces........... 2 Identifiers...................................................2 Objects nd ! mes" #eference $ounting.. 2 %ut ble&Immut ble Objects.......................2 ! mesp ces.............................................. 2 $onst nts" 'numer tions...........................2 )lo- Control............................................ 2 $ondition....................................................2 (oop...........................................................2 Functions&methods e)it............................. 2 ')ceptions................................................. 2 Iter ble *rotocol.........................................2 1nter(retation 2 "*ecution....................... 2 )unctions 6efinitions 0 7sa+e................ 2 * r meters & #eturn + lue.........................2 ( mbd functions...................................... 2 $ ll ble Objects.........................................2 $ lling Functions........................................2 Functions $ontrol.......................................2 ,ecor tors................................................. 2 8y(es2Classes 0 ' 3ects......................... 9 $l ss ,efinition..........................................Object $re tion..........................................$l sses . Objects #el tions.......................Attributes % nipul tion............................. Speci l %ethods.........................................,escriptors protocol...................................$opying Objects.........................................Introspection..............................................:odules and Packa+es............................ 9 Source encodings...................................... Speci l Attributes.......................................:ain "*ecution 2 /cri(t Para$eters........ 9 '(erators................................................ 4 *riority....................................................... / Arithmetic Oper tors................................. / $omp rison Oper tors.............................../ Oper tors s Functions............................../ .ooleans................................................. 4 5u$ ers..................................................4 Oper tors.................................................../ Functions................................................... / .it Le#el '(erations................................ 5 Oper tors...................................................0 /trin+s..................................................... 5 'sc pe se1uences..................................... 0 2nicode strings..........................................0 %ethods nd Functions..............................0 Form ting.................................................. 0 $onst nts...................................................3 #egul r ')pressions.................................. 3 (oc li4 tion................................................3 %ultilingu l Support...................................5 Containers............................................... 7 Oper tions on $ont iners.......................... 5 $opying $ont iners....................................6 O+erriding $ont iners Oper tions............. 6 /e;uences...............................................< (ists . Tuples.............................................6 Oper tions on Se1uences..........................6 Inde)ing.....................................................6 Oper tions on mut ble se1uences............ 6 O+erriding Se1uences Oper tions............. 6 :a((in+s =dictionaries>........................... < Oper tions on % ppings............................ 6 O+erriding % pping Oper tions.................6 Other % ppings......................................... 6 /ets......................................................... < Oper tions on Sets.................................... 6 'ther Containers /tructures4 ?l+orith$s @ Arr y..........................................................7 8ueue........................................................ 7 *riority 8ueues.......................................... 7 Sorted (ist..................................................7 Iter tion Tools............................................7 6ate 0 8i$e............................................ @ %odule time...............................................7 %odule d tetime........................................7 %odule timeit.............................................7 Other %odules......................................... 19 )iles.......................................................&0 File Objects.............................................. 19 (o:;le+el Files......................................... 19 *ipes........................................................ 19 In;memory Files....................................... 19 Files Inform tions.................................... 19 Termin l Oper tions................................ 11 Tempor ry Files....................................... 11 * th % nipul tions.................................. 11 ,irectories............................................... 11 Speci l Files.............................................11 $opying" %o+ing" #emo+ing.................... 11 'ncoded Files...........................................11 Seri li4 tion............................................. 12 *ersistence.............................................. 12 $onfigur tion Files...................................12 "*ce(tions.............................................&2 St nd rd ')ception $l sses.....................12 < rnings..................................................12 ')ceptions *rocessing............................. 12 "ncodin+ - 6ecodin+............................. &2 8hreads 0 /ynchroniAation................... &2 Thre ding Functions................................ 12 Thre ds....................................................1%utu l ')clusion......................................1'+ents......................................................1Sem phores.............................................1$ondition = ri bles..................................1Synchroni4ed 8ueues.............................. 1Process..................................................&9 $urrent *rocess....................................... 1Sign l > ndling........................................1/ Simple ')tern l *rocess $ontrol..............1/ Ad+ nced ')tern l *rocess $ontrol......... 1/ B:L Processin+..................................... &5 SA? ; '+ent;dri+en...................................10 ,O% ; In;memory Tree............................ 13 6ata ases............................................. &7 @eneric ccess to ,B%;style ,Bs............ 15 St nd rd ,B A*I for S8( d t b ses........ 15 .ulk....................................................... &7

/tyles C keyword function2method type replaced_expression variable literal module module_filename language_syntax 5otations C f()A return + lue f()B return nothing CprocedureD [x] for a list of x data4 (x) for a tuple of x data4 $ay ha#e x{n}D n ti$es x data.

Types basestring1 bool buffer complex dict exception file float frozenset int list long object set slice str tuple type unicode xrange & asestrin+ is #irtual su(erclass of str and unicode. 8his doc uses string -hen unicode and str can a((ly. Functions Constructor functions of uiltin ty(es are directly accessi le in uiltins. __import__ abs apply callable chr classmethod cmp coerce compile delattr dir divmod enumerate eval execfile filter getattr globals hasattr hash help hex id input intern! isinstance issubclass iter len locals map max min oct open ord pow property range raw_input reduce reload repr reversed round setattr sorted staticmethod sum super unichr vars "ip & 7se f=Sar+s4SSkar+s> in (lace of a((ly=f4ar+s4kar+s>. 2 6onOt use intern.

ENVIRONMENT VARIABLES
PE8F'5C?/"', PE8F'56".7G PE8F'5F':" no case distinction in $oduleDfile $a((in+ H -d co$$and-line o(tion :odify standard Python li s (refi* and e*ec (refi* locations. 7se <prefix>[:<execprefix>!. & PE8F'515/P"C8 H -i co$$and-line o(tion & PE8F'5'P81:1I" H -' co$$and-line o(tion PYTHONPATH 6irectories -here Python search -hen i$(ortin+ $odules2(acka+es. /e(arator C =(osi*> or J =-indo-s>. 7nder -indo-s use re+istry F,L:K/of-areKL. PE8F'5/8?R87P )ile to load at e+inin+ of interacti#e sessions. PE8F'575.7))"R"6 & H -u co$$and-line o(tion & PE8F'5%"R.'/" H -# co$$and-line o(tion & 1f set to non-e$(ty #alue.
& &

STATEMENTS
'ne state$ent (er line&. Can continue on ne*t line if an e*(ression or a strin+ is not finished = ( [ # $$$ %%% not closed>4 or -ith a & at end of line. Char ' start co$$ents u( to end of line. pass 5ull state$ent. assert expr[(message! ?ssertion check e*(ression true. del name[4! Re$o#e na$e D o 3ect indin+. print [))obj(![expr[4![(! Mrite expr to sys.stdout2. exec expr [in globals [4 locals!! "*ecute expr in na$es(aces. fct=[expr[(!!([name*expr[(!! Call any calla le o 3ect fct -ith +i#en ar+u$ents =see )unctions 6efinitions 0 [(+args![(++kwargs!> 7sa+e - (2>. name[(! * expr ?ssi+n$ent o(erator9. :ulti(le state$ents on sa$e line usin+ , se(arator - a#oid if not necessary. 2 Mrite to any s(ecified o 3ect follo-in+ file interface =-rite $ethod>. Mrite s(ace et-een e*(ressions4 line-return at end of line e*ce(t -ith a final (. 9 Left (art na$e can e container e*(ression. 1f e*(r is a se;uence of $ulti(le #alues4 can un(ack into $ulti(le na$es. Can ha#e $ulti(le assi+n$ents of sa$e #alue on sa$e line C a H H c H e*(r. 'ther state$ents =loo(s4 conditionsL> introduced in res(ecti#e (arts. Blocks ? : et-een state$ents defines de(endant state$ents4 -ritten on sa$e line or -ritten on follo-in+ line=s> -ith dee(er indentation. .locks of state$ents are si$(ly lines at sa$e indentation le#el. if x<= ! return 1 if asin"#$%pi&' ! a = pi&( b = )pi&( else ! a = asin"#$ b = pi&()a /tate$ent continuation lines donOt care indentation. 8o a#oid (ro le$s4 confi+ure your editor to use 4 s(aces in (lace of ta s. Assignment Shortcuts a -* b a .* b a +* b a //* b a 0* b a ++* b a 1* b a 2* b a 3* b a /* b a ))* b a 44* b
&

COMMAND-LINE OPTIONS
python [-d"hi'Q/tu7#%M*! [-c cmd N -$ mod N file N -! [args! -d 'ut(ut de u++in+ infos fro$ (arser. -" 1+nore en#iron$ent #aria les. -h Print hel( and e*it. -i )orce interacti#e $ode -ith (ro$(t =e#en after scri(t e*ecution>. -' '(ti$iAe +enerated ytecode4 re$o#e assert checks. -'' ?s -' and re$o#e docu$entation strin+s. -Q arg 6i#ision o(tion4 arg in [old=default>4warn4warnall4new!. -/ 6onOt i$(ort site.(y definitions $odule. -t Marn inconsistent ta 2s(ace usa+e =-tt e*it -ith error>. -u 7se un uffered inary out(ut for stdout and stderr. -7 )orce use of unicode literals for strin+s. -# 8race i$(orts. -% Print #ersion nu$ er and e*it. -M arg "$it -arnin+ for arg PactionC$essa+eCcate+oryC$oduleClinenoP -* /ki( first line of source =fort non-7ni* for$s of QRc$d>. -c cmd "*ecute cmd. -$ mod /earch $odule mod in sys.(ath and runs it as $ain scri(t. file Python scri(t file to e*ecute. args Co$$and-line ar+u$ents for cmd2file4 a#aila le in sys.argv[1:].

FILES EXTENSIONS
.pyHsource4 .pycH ytecode4 .pyoH ytecode o(ti$iAed4 .pydH inary $odule4 .dll2.soHdyna$ic li rary. .pywHsource associated to (ython-.e*e on Mindo-s (latfor$4 to run

-ithout o(enin+ a console.

LANGUAGE KEYWORDS
List of key-ords in standard $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 reser#ed4 ut a#oid to redefine it. 6onOt redefine these constants C None4 True4 False.

BUILTINS
?#aila le directly e#ery-here -ith no s(ecific i$(ort. 6efined also in $odule __builtins__. 1a 1b

"#aluate a once4 and assi+n to a the result of o(erator efore * a((lied to current a and b. "*a$(le C a0*b T a*a0b

CONSOLE

INTERACTIVE INPUT!OUTPUT
1c

print expression[4L!

input([prompt!) A e+ lu tion of user input Ctyped d t D raw_input([prompt!) A strE user input s r : string 6irect $ani(ulation =redefinition> of stdin2stdout2stderr #ia sys $odule C sys.stdin sys.stdout sys.stderr sys.__stdin__ sys.__stdout__ sys.__stderr__ ?ll are files or files-like o 3ects. 8he __xxx__ for$s kee( access to ori+inal standard 1' strea$s. Ctrl-C raises *eyboard+nterrupt e*ce(tion. _ A + lue of l st e)pression e+ lu tion help([object!) B print online document tion sys.displayhook A Cr:D fctC+ lueD c lled to displ y + lue sys.__displayhook__ A b ckup of origin l displ yhook function sys.ps A strE prim ry interpreter prompt sys.ps! A strE second ry Ccontinu tionD interpreter prompt /ee e*ternal (acka+e ipython for an enhanced interacti#e Python shell.

$ethods>. 5a$es(aces can e nested4 inner na$es(aces hiddin+ identical na$es fro$ outer na$es(aces. dir([object!) A listE n mes defined in object n mesp ce1 vars([object!) A dict2E identifierE+ lue of object s n mesp ce1 1 if o 3ect not s(ecified use nearest na$es(ace =locals>. 2 $ust not e $odified. !onstants, $numerations 7se u((ercase and U for constants identifiers =+ood (ractice>. :ay define na$es(aces to +rou( constants. Cannot a#oid +lo al2local na$e redefinition =can e#entually define na$es(aces as classes -ith attri utes access control - not in Python s(irit4 and e*ecution cost>. /ee third (arty $odules pyenum for strict enu$-like na$es(ace.

Generators )unctions retainin+ their state et-een t-o calls. Return #alues usin+ yield. /to( +eneration #ia si$(le return or #ia raise 0top+teration. &> uild +enerator fro$ function C gen*generatorfct(args) 2> use gen.next=> #alues until 0top+teration is raised. Generator itera le e*(ressions -ith C (x for x in iterable where cond> Operations with/on Iterable /ee '(erations on Containers =(7>. /ee 1teration 8ools =(@>.

INTERPRETATION ! EXECUTION
compile(string1(filename(kind2[(flags3[(dont_in erit3!!) A code object eval(expression[(globals[(locals!!) A + lueE e+ lu tion/ of expression string eval(code_object[(globals[(locals!!) A + lueE e+ lu tion/ of code_object exec6 statements [in globals[(locals!! B statements string1 e)ecuted/ execfile(filename[(globals[(locals!!) B file filename interpreted/
&

FLOW CONTROL
!ondition if cond : inst [ elif cond : inst ! [ else : inst ! %oop for var[(! in iterable : inst [ else : inst !

OB"ECTS# NAMES

AND

NAMESPACES

Identifiers 7se C [a-A?-IU![a-A?-I0-@U!S /(ecial usa+e for underscore C ,xxx +lo al not i$(orted y import ,xxx i$(le$entation detail4 for internal use =+ood (ractice> ,,xxx O(ri#ateO class $e$ ers4 defined as ,.lassName,,xxx ,,xxx,, nor$ally reser#ed y Python Case is si+nificant C This,Name RH T/+0,N123. Objects and Names, eference !ounting 6ata are ty(ed o 3ects =all data>4 na$es are dyna$ically ound to o 3ects. * assi+n$ent state$ent ind result of ri+ht (art e#aluation into left (art na$e=s>2container=s>. "*a$(les C a = 4-c56 a8b = "7/ello7879orld7$ x8y8tabz<i= = fct"i$ s = 7/ello7 pi8e = 4:1'8(:;1 a8b = b8a Mhen an o 3ect is no lon+er referenced = y na$es or y containers>4 it is destroyed =its __del__ $ethod is then called>. sys.getrefcount(object)A intE current reference counter of object /tandard $odule weakref define tools to allo- o 3ects to e +ar a+e collected -hen necessary and dyna$ically re-created on-de$and. "utable#Immutable Objects :uta le o 3ects can e $odified in (lace. 1$$uta le o 3ects cannot e $odified =$ust uild a ne- o 3ect -ith ne- #alue>. I$$%t&'() C bool4 int4 long4 float4 complex4 string4 unicode4 tuple4 frozenset4 buffer4 slice. M%t&'() C list4 set4 dict and other hi+h le#el class o 3ects. 8here is no constant definition. Vust use u((ercase na$es to identify sy$ ols -hich $ust not e $odified. Namespaces Places -here Python found na$es. .uiltins na$es(ace D na$es fro$ $odule __builtins__4 already a#aila le. Glo al na$es(ace D na$es defined at $odule le#el =Aero indentation>. Local na$es(ace D na$es defined in $ethods2functions. del name B remo+e e)isting n me from n mesp ce Cremo+e object bindingD globals() A dictE identifierA+ lue of glob l n mesp ce locals() A dictE identifierA+ lue of loc l n mesp ce Current sco(e D na$es directly usa le. /earched in locals4 then locals fro$ enclosin+ definitions4 then +lo als4 then uiltins. 'ut-of-sco(e na$e D use the dotted attri ute notation x.y =$ay e x.y.".t>L -here x is a na$e #isi le -ithin the current sco(e. Class na$es(ace D na$es defined in a class =class $e$ ers>. ' 3ect na$es(ace D na$es usa le -ith object.name notation =attri utes4 2a

while cond : inst 8here is no Os-itchO or OcaseO. [ else : inst ! Can use if elif elifL else. "*it loo( -ith break. Can use a $a((in+ -ith Go to ne*t iteration -ith continue. functions ound to cases. Loo(s else locs only e*ecuted -hen loo( e*it nor$ally =-ithout break>.

:ulti-line state$ents in source code $ust use >n as ne-line4 and $ust e ter$inated y a ne-line. ,ind relati#e to strin+ content4 ?exec? D se;uence of state$ents4 ?e#al? D sin+le e*(ression4 ?single? D sin+le interacti#e state$ent. 9 )la+s and dontUinherit are for future state$ents =see doc>. 4 1n conte*t of +lo als and locals na$es(aces. 5 "*ec is a lan+a+e state$ent4 others are uiltin functions.
2

Functions#methods e&it "*it function2$ethod -ith return [value! "*it fro$ +enerator ody -ith yield value :ulti(le returned #alues usin+ tuple data. Cannot yield -ithin a try2finally lock. $&ceptions try : inst except [ except_class [(value !! : inst L [ else : inst ! Can ha#e a tu(le of classes for e*ce(tUclass. 5ot s(ecifyin+ a class catch all e*ce(tions. .lock else e*ecuted -hen try lock e*it nor$ally. try : inst finally : inst Process finally lock in all e*ecution (aths =nor$al or e*ce(tion>. raise exception_class[(value[(traceback!! raise exception_object raise Last for$ re-raise the currently catched e*ce(tion in an e*ce(tion handler. Iterable 'rotocol Generic and si$(le (rotocol allo-in+ to iterate on any collection of data. ' 3ects of class definin+ __iter__ or __getitem__ are itera le =directly usa le in for loo(s>. __iter__(self) A iter tor on self iter(object) A iter tor on iter ble object iter(callable(sentinel) A iter tor returning c ll bleCD + lues up to sentinel enumerate(iterable)A iter tor returning tuples Cinde)"+ lueD from iter ble Iterators Objects Interface next(self)A ne)t item1 __iter__(self)A iter tor object itself & Mhen reach end of collection4 raise 0top+teration e*ce(tion on su se;uent calls =ie. iterator usa le only one ti$e on a collection>. 2b

FUNCTIONS DEFINITIONS

USAGE

def fctname([paramname[*defaultvalue![(L!! [(+args![(++kwargs!) : instructions new.function(code(globals[(name[(argdefs!!) A python function Csee docsD 'arameters # eturn (alue Para$eters are (assed y references to o 3ects. Eou can $odify #alues of $uta le o 3ects ty(es. Eou cannot $odify #alues of i$$uta le o 3ects ty(es - as if they -ere (assed y #alue. 5otation + D #aria le list of anony$ous (ara$eters in a tuple. 5otation ++ D #aria le list of na$ed (ara$eters in a dict. Return #alue=s> -ith return [value[(L!! )or $ulti(le #alues4 return a tuple. 1f no return #alue s(ecified or if end of function definition reached4 return None #alue. %ambda functions lambda param[(L! : expression ?nony$ous functions defined inline. Result of expression e#aluation is returned =it $ust e an e*(ression4 no loo(4 no condition>. "*(ression uses #alues kno-n at definition ti$e =e*ce(t for (ara$s>. !allable Objects ' 3ects ha#in+ a __call__ $ethod can e used as functions. :ethods ound to o 3ects can e used as functions C f * o.met callable(x) A boolE test x c ll ble :ith xCFD !alling Functions [name*! fctname(!expr[(L!![(name=expr[(L![(+args![(++args!) ?nony$ous (ara$eters (assed in (ara$eters order declaration. Para$s ha#in+ default #alue can e o$itted. 5otation + D (ass #aria le list of anony$ous (ara$eters in a tuple. 5otation ++ D (ass #aria le list of na$ed (ara$eters in a dict. Functions !ontrol sys.getrecursionlimit()A intE current recursion limit for functions sys.setrecursionlimit(limit) B set recursion limit for functions )ecorators Glue code =functions> called at functions and $ethods definitions ti$e4 return the final function2$ethod =+enerally -ith -ra((in+ code>. 2c

5decoratorname [(decorator_arguments>! [L! def fct(fct_rguments):L 5dec1 5dec2(args) 5dec3 def fct(L):L
like

&

1f donOt return a classref o 3ect4 then o 3ect.UUinitUU is called -ith initar+s. Object Cast __repr__(self)A strE c lled for repr(self) nd 8self8 __str__(self> A strE c lled for str(self) nd print self __coerce__(self(ot er) A + lue" c lled for coerce(self(ot er) Object Hash Key __hash__(self)A intE -2 bits h sh code for object" used for hash(obj) nd 1uick dict m pping keys comp rison ; def ult implement tion use hash(id(self)) Attributes access /ee also P6escri(tors (rotocolP infra. __getattr__(self(name)A + lue" c lled for undefined ttributes __getattribute__(self4 name)A + lue" l: ys c lled __setattr__(self4 name( value) B c lled for obj.name*value __delattr__(self4 name) B c lled for del obj.name __call__(self4 +args( ++kwargs)A + lue" c lled for obj(() Static etho! / Class etho! 7se standard decorators =see 6ecorators (2>. class Class5a$e C 5staticmethod def met odname(*): L 5classmethod def met odname(classref(L): L )escriptors protocol 6escri(tors are attri ute o 3ects controlin+ access to attri utes #alues. 8hey $ust define so$e of follo-in+ $ethods C __get__(self(obj(ownerclass)A ttribute + lue for obj __set__(self(obj(value) B modify ttribute in obj" set to value __delete__(self(obj) B remo+e ttribute from obj 1n these $ethods self is the descri(tor o 3ect4 and obj is the tar+et o 3ect -hich attri ute is $ani(ulated. "roperties ? descri(tor to directly ind $ethods2functions to control attri ute access. 7se uiltin ty(e property -ith init ar+s. class *+%lass : attributename * property(getter(setter(deleter(description) "ach init ar+ default to 5one =ie. undefined>. !opying Objects ?ssi+n$ent only du(licate references. 8o shallo- co(y an o 3ect = uild a ne- one -ith sa$e #alues - referencin+ sa$e content>4 or to dee( co(y an o 3ect =dee(-co(yin+ referenced content>4 see o 3ect co(y $ethods4 and functions in standard $odule copy. copy.copy(object)A + lueE sh llo: copy of object copy.deepcopy(object[[(memo!(_nil!)A + lueE deep copy of object1 & Para$s memo and nil are used in recursi#e dee(co(y4 their default #alues are None and e$(ty list. Copy "rotocol __copy__(self)A + lueE sh llo: copy of self" c lled by copy.copy(() __deepcopy__(self(memo)A + lueE deep copy of self" c lled by copy.deepcopy(() )or co(yin+4 o 3ects can define (icklin+ (rotocol too =see )iles /erialiAation - (&2>4 in (lace of __copy__ and __deepcopy__. Introspection .eyond this docu$entation. :any __xxx___ attri utes are defined4 so$e are -rita le =see other docs>. /ee standard $odule inspect to $ani(ulate these data.

#$a ple of Introspection Attributes 5oteC classes are o 3ects tooR __base__ A listE p rent cl sses of cl ss __slots__ A tupleE llo:ed objects ttributes n mes1 of cl ss __class__ A cl ss&typeE objectGs cl ss __dict__ A dictE defined ttributes Cobject n mesp ceD of n inst nce __doc__ A stringE document tion string of p ck ge" module" cl ss" function __name__ A strE object definition n me of function __file__ A stringE p thn me of lo ded module .pyc" .pyo or .pyd & List of allo-ed attri utes na$es. 7sa+e discoura+ed.

B /ee (a+e Python6ecoratorLi rary in (ython.or+ Miki for so$e decorators definitions.

def fct(L):L fct * dec1(dec2"args#(dec3(fct))))

TYPES!CLASSES

OB"ECTS

?ll data are ty(ed o 3ects relyin+ to classes. type(o) A typeE type object of o /tandard $odule types define ty(e o 3ects for uiltins ty(es. !lass )efinition class classname [(parentclass[(L!)! C varname H expr B + rn me defined in cl ssn me n mesp ce def metname(self[(L!): B define methods like functions /u((ort $ulti(le inheritance. Can inherit fro$ uiltin class. 1nherit at least fro$ object ase class HW Python One- style classO. )irst (ara$eter of $ethods is tar+et o 3ect4 standard use self na$e. ?ccess class $e$ ers #ia class na$e4 o 3ect $e$ ers #ia self. 8his doc consider you use ne- style class =inheritin+ fro$ object>. new.classob6(name(baseclasses(dict) A ne: cl ss Csee docsD new.instancemethod(fct(instance(class) A ne: methodE bound to instance it it is not None" see docs Metaclass Class definition create a ne- ty(e. 1t can e done O y handO -ith C x H type($classname$4(parentclass([L!)(#varname:expr[(L!7 def metname(self[(L!): x.metname * metname 8his allo- creation of $etaclass class =class uildin+ other class>. Object !reation obj * %lass&ame(initargsL) 1n case of e*ce(tion durin+ initialiAation4 o 3ect is destroyed -hen e*itin+ init code =reference counter reach Aero>. new.instance(class[(dict!) A objectE cre te ne: class inst nce :ithout c lling __init__ method" dict is initi l object ttributes !lasses * Objects elations isinstance(obj(classinfo) A boolE test object kind of type&cl ss cl ssinfo issubclass(aclass(aparent) A boolE test s me cl ss or p rent rel tionship Prefer isinstance=> to ty(e=> for ty(e checkin+. Parent class $ethods are not auto$atically called if o#erriden in su class - they $ust e e*(licitly called if necessary. Call (arent $ethods #ia super function C super(' is%lass(self).met odname(self(args() 'r the old -ay4 #ia (arent class na$es(ace C )arent%lass.met odname(self(args) Attributes "anipulation object.name * value setattr(object(name(value) B object ttribute set to + lue object.name A value of object attribute getattr(object(name[4default!)A + lue of object ttribute del object.name delattr(object(name) B object ttribute remo+ed Special "ethods 'ther s(ecial o#errida le UU***UUU $ethods are listed in res(ecti#e sections. Object Life __new__(classref(initargsL)A object of cl ssref type" lre dy initi li4ed1 __init__ =self(initargsL)B c lled to initi li4e object :ith init rgs __del__ (self)B c lled :hen object :ill be destroyed 3a

MODULES

AND

PACKAGES

)ile gabuzo.py X $odule gabu"o. 6irectory kramed/ -ith a file __init__.py B packa+e kramed. Can ha#e su -(acka+es =su directories ha#in+ __init__.py file>. /earched in the Python PATH. Current Python P?8F stored in sys.path list. Contains directories and .Ai( files (aths. .uilt fro$ location of standard Python $odules4 PE8F'5P?8F en#iron$ent #aria le4 directory of $ain $odule +i#en on co$$and line4 data s(ecified in lines of %pth files found in Python ho$e directory4 and data s(ecified in re+istry under Mindo-s. Current list of loaded $odules stored in sys.modules $a( =$ain $odule is under key ,,main,,>. import module [as alias! [(! from module import name [as alias! [(! from module import + reload(module) B module is relo ded Cbut e)isting references still refer old module contentD new.module(name[(doc!) A ne: module object. 1$(ort can use (acka+e (ath =e*Cfrom encoding.aliases import>. 6irect i$(ort fro$ a (acka+e use definitions fro$ __init__.py file. %ery careful -ith import + as i$(orted na$es o#erride na$es already defined. 8o li$it your $odules na$es e*(orted and #isi le y import +4 define $odule +lo al __all__ -ith list of e*(orted na$es =or use +lo al na$es _xxx>. /ee __import__ uiltin function4 and $odules imp4 ihooks. __import__(modulename[4 globals[4locals[4lnameslist!!!) Source encodings /ee P"P 2Y9. 6eclare source files encodin+ in first or second line in a s(ecial co$$ent. @ )-) coding! encoding_name )-) 1f this is not s(ecified4 Python use sys.getdefaultencoding() #alue =see $odules sitecustomize.py and user.py>. 1t is i$(ortant to s(ecify encodin+ of your $odules as uPLP strin+s use it to correctly uild unicode literals. Special Attributes __name__ A strE module n me" ?,,main,,? for comm nd;line c lled script __file__ A stringE p thn me of compiled module lo ded

MAIN EXECUTION ! SCRIPT PARAMETERS


8he O$ainO $odule is the $odule called #ia co$$and-line =or e*ecuted y shell -ith first scri(t line #! /bin/env python>. Co$$and-line (ara$eters are a#aila le in sys.argv =a (ython list>. ?t end of $odule4 -e $ay ha#e C if ,,name,,==?,,main,,? ! @ main code @ generally call a ?main? function! mainfunction"sys:arg#<1!=$ @ or in lib modules8 execute test&demo code::: "*ecution e*it after last $ain $odule instruction =in $ultithread4 -ait also for end of non-dae$on threads>4 unless interacti#e $ode is forced. 3c

3b

Can force e*it -ith callin+ sys.exit(code)4 -hich raise a 0ystem3xit e*ce(tion - see Current Process - "*itin+ =(&9>.

Operators as Functions '(erators are also defined as functions in standard operator $odule. Co parison lt(a(b) H __lt__(a(b) le(a(b) H __le__(a(b) e;(a(b) H __e;__(a(b) Lo'ical / (oolean not_(o) H __not__(o) truth(o) is_(a(b) is_not(a(b) Arith etic abs(o) H add(a(b) sub(a(b) mul(a(b) div(a(b) mod(a(b) __abs__(o) H __add__(a(b) H __sub__(a(b) H __mul__(a(b) H __div__(a(b) H __mod__(a(b) truediv(a(b) H __truediv__(a(b) floordiv(a(b) H __floordiv__(a(b) neg(o) H __neg__(o) pos(o) H __pos__(o) pow(a(b) H __pow__(a(b) and_(a(b) H __and__(a(b) or_(a(b) H __or__(a(b) xor(a(b) H __xor__(a(b) ne(a(b) H __ne__(a(b) ge(a(b) H __ge__(a(b) gt(a(b) H __gt__(a(b)

OPERATORS
6eal -ith arith$etic4 oolean lo+ic4 it le#el4 inde*in+ and slicin+. 'riority
& =a(> [a(] Y x-+ && x4+ x4*+ x)+ x)*+ x**+ x9*+

#a:b47 88
2 s[i] s[i:j] 9 -x .x :x 4 x+++ 5 x++ x/+ x0+

x.+
7 x<<+

x4)+ x is + x is not + x in s x not in s


&2 not x &9 x and + &4 x or + &5 lambda args:expr

s.attr f()

x))+

< x1+ @ x3+ &0 x2+

long(expr[(base-1.!) A longE c st of expr .uiltin floatin+ (oint ty(es C float =like C dou le>4 complex =real and i$a+inary (arts are float>. float(expr) A float/ representation of expr complex(x[4+!> A complex/ number/ x0+j [x[!+6 A complex/ number1 ex/ 302j 3452j c.real A float/ real part of complex number c.img A float/ imaginar+ part of complex number c.con6ugate() A complex/ conjugate of complex number "real13img# :a*i$u$ int inte+er in sys.$a*int. ?uto$atic con#ersions et-een nu$eric ty(es. ?uto$atic con#ersions fro$ int to lon+ -hen result o#erflo- $a* int. 6irect con#ersions fro$2to strin+s fro$2to int4 lon+L #ia ty(es constructors. 8y(e Aecimal defined in standard $odule decimal. .ase fi*ed ty(e co$(act stora+e arrays in standard $odule array. Operators .x -x x-+ x.+ x++ x/+ & x//+ & x0+ 2 x+++ 2 & Mith from __future__ import di#ision4 / is true di#ision =1/(D :6>4 and // is floor di#ision =1//(D >. "lse for inte+ers / is still floor di#ision. 2 0 is re$ainder o(erator4 ++ is (o-er ele#ation o(erator =sa$e as pow>. Functions /o$e functions in uiltins. abs(x) A bsolute + lue of x divmod(x(y) A (x6+(x7+) oct(integer) A strE oct l represent tion of integer number hex(integer) A strE he) decim l represent tion of integer number Re(resentation for$atin+ functions in strin+s )or$atin+ =(5> and LocaliAation =(Y>. Math ,unctions /tandard floatin+ (oint functions2data in standard math $odule. acos(x) A floatE r di ns ngle for x cosinus + lue E K;1F1L AK9FNL asin(x) A floatE r di ns ngle for x sinus + lue E K;1F1L AK;N&2FON&2L atan(x) A floatE r di ns ngle for x t ngent + lue E K;PFPL AL;N&2FON&2K atan!(x(+) A floatE r ndi ns ngle for x&+ t ngent + lue ceil(x) A floatE sm llest integr l + lue JI x cos(x) A floatE cosinus + lue for r di ns ngle x cosh(x) A floatE hyperbolic cosinus + lue for r di ns ngle x exp(x) A floatE e)ponenti l of x I ex fabs(x) A floatE bsolute + lue of ) floor(x) A floatE l rgest integr l + lue HI x fmod(x(+) A floatE modulo I rem inder of x&+ frexp(x) A Cfloat"intDE Cm"yD m m ntiss of x" y e)ponent of x Q :here xImR2y ldepx(x(i) A floatE x multiplied by 2 r ised to i po:erE x R 2i log(x) A floatE neperi n log rithm of x log B(x) A floatE decim l log rithm of x modf(x) A CfloatS2TDE Cf"iD f signed fr ction l p rt of x" i signed integer p rt of x pow(x(+) A floatE x r ised to + po:er Cx+D sin(x) A floatE sinus + lue for r di ns ngle x sinh(x) A float: hyperbolic sinus value for radians angle x s;rt(x) A floatE s1u re root of x CUxD tan(x) A floatE t ngent + lue for r di ns ngle x tanh(x) A float: hyperbolic tangent value for radians angle x pi A floatE + lue of N CpiI4:1'16B(C646DB;B41D e A floatE + lue of neperi n log rithms b se CeI(:;1D(D1D(D'6B '61D :odule cmath (ro#ides si$ilar functions for complex nu$ ers. -an!o .u bers 4c Rando$iAation functions in standard random $odule. :odule functions

Arithmetic Operators Can e defined for any data ty(e. Arith etic O&erri!in' __add__(self(ot er) A + lueE c lled for self - ot er __sub__(self(ot er) A + lueE c lled for self . ot er __mul__(self(ot er) A + lueE c lled for self + ot er __div__(self(ot er) A + lueE c lled1 for self / ot er __truediv__(self(ot er) A + lueE c lled2 for self / ot er __floordiv__(self(ot er) A + lueE c lled for self // ot er __mod__(self(ot er) A + lueE c lled for self 0 ot er __divmod__(self(ot er) A + lueE c lled for divmod(self(ot er) __pow__(self(ot er) A + lueE c lled for self ++ ot er __non"ero__(self)A + lueE c lled for non"ero(self) __neg__(self) A + lueE c lled for .self __pos__(self) A + lueE c lled for -self __abs__(self) A + lueE c lled for abs(self) __iadd__(self(ot er) B c lled for self -* ot er __isub__(self(ot er) B c lled for self .* ot er __imul__(self(ot er) B c lled for self +* ot er __idiv__(self(ot er) B c lled1 for self /* ot er __itruediv__(self(ot er) B c lled2 for self /* ot er __ifloordiv__(self4 ot er) B c lled for self //* ot er __imod__(self(ot er) B c lled for self 0* ot er __ipow__(self(ot er) B c lled for self ++* ot er & -ithout 2 2 -ith fro$ UUfuturUU i$(ort di#ision .inary o(erators __xxx__ ha#e also __rxxx__ for$s4 called -hen tar+et o 3ect is on ri+ht side. !omparison Operators '(erators can co$(are any data ty(es. Co$(are +&(%), -ith 4 4* ) )* ** 9* 4). 8est o 3ects -.)nt-ty -ith is and is not =co$(are on id(obj)>. 6irect co$(osition of co$(arators is allo-ed in e*(ressions C x4+4*,)t. .uiltin function cmp(o1(o2) A )1 =o1 Z o2>4 =o1 HH o2>4 1 =o1 W o2> Co parison O&erri!in' lled for self 4 ot er lled for self 4* ot er lled for self ) ot er lled for self )* ot er lled for self ** ot er lled for self 9* ot er nd for self 4) ot er __cmp__(self(ot er)A intE c lled for self comp red to other" selfHot erA+ lueH9" selfIIot erA+ lueI9" selfJotherA+ lueJ9 & ?ny #alue usa le as oolean #alue4 or a <ot=mplemented #alue if cannot co$(are -ith such other ty(e. __lt__(self( __le__(self( __gt__(self( __ge__(self( __e;__(self( __ne__(self( 4a ot ot ot ot ot ot er)A bool1E c er)A bool1E c er)A bool1E c er)A bool1E c er)A bool1E c er)A bool1E c

(it Le&el lshift(a(b) H __lshift__(a(b) rshift(a(b) H __rshift__(a(b) inv(o) H invert(o) H __inv__(o) H __invert__(o) Se)uences concat(a(b) H __concat__(a(b) contains(a(b) H __contains__(a(b) count>f(a(b) index>f(a(b) repeat(a(b) H __repeat__(a(b) setitem(a(b(c) H __setitem__(a(b(c) getitem(a(b) H __getitem__(a(b) delitem(a(b) H __delitem__(a(b) setslice(a(b(c(v) H __setslice__(a(b(c(v) getslice(a(b(c) H __getslice__(a(b(c) delslice(a(b(c) H __delslice__(a(b(c) *ype *estin' 8hese functions $ust e considered as not relia le. is?apping@ype(o) is<umber@ype(o) isAe;uence@ype(o) Attribute an! Ite Loo+up attrgetter(attr) A fctE :here fctC)DA).attr itemgetter(item) A fctE :here fctC)DA)KitemL

BOOLEANS
)alse C None4 Aero nu$ ers4 e$(ty containers. False D . 8rue C if not false. True D 1. bool(expr) A True M False Lo+ical not C not expr Lo+ical and C expr1 and expr2 Lo+ical or C expr1 or expr2 Lo+ical and and or use short (ath e#aluation. (ool Cast O&erri!in' __non"ero__(self) A boolE test object itself1 & 1f UUnonAeroUU undefined4 look at UUlenUU4 else o 3ect is true.

NUMBERS
.uiltin inte+er ty(es C int =like C lon+>4 long =unli$ited inte+er> int(expr[(base-1.!) A intE c st of expr 4b

use an hidden4 shared state4 Eandom ty(e +enerator =unifor$ distri ution>. )unctions also a#aila le as $ethods of Eandom o 3ects. seed([*!) B initi li4e r ndom number gener tor random()A floatE r ndom + lue in K9.9" 1.9K randint(a4b)A intE r ndom + lue in Ka" bL uniform(a4 b)A floatE r ndom + lue in Ka" bK getrandbits(k)A longE :ith k r ndom bits randrange([start(!stop[(step!)A intE r ndom + lue in range(start( stop( step) choice(se8)A + lueE r ndom item from se8 se1uence shuffle(x[(rndfct!) B items of x r ndomly reordered using rndfctCD sample(population4k)A listE k r ndom items from polulation ?lternate rando$ distri utions C betavariate(alp a(beta)4 expovariate(lambd)4 gammavariate(alp a4beta)4 gauss(mu(sigma)4 lognormvariate(mu( sigma)4 normalvariate(mu(sigma)4 vonmisesvariate(mu(kappa)4 paretovariate(alp a)4 weibullvariate(alp a(beta). ?lternate rando$ +enerator 9ichmann/ill class. 6irect +enerator $ani(ulation C getstate()4 setstate(state)4 6umpahead(n). 1n $odule os4 see C os.urandom(n) A strE n r ndom bytes suit ble for cryptogr phic use Other Math Mo!ules ?d#anced $atri*4 al+orith$s and nu$ er crunchin+ in third (arty $odules like numpy =e#olution of numarray 2 <umeric>4 gmpy =$ulti(recision arith$etic>4 Cec=nt4 scipy4 pyarray4 L /ee sites /ciPy4 .ioPython4 Py/cience4L .u bers Casts O&erri!in' __int__(self) A int! c lled for int(self) __long__(self) A long! c lled for long(self) __float__(self) A float! c lled for float(self) __complex__(self) A complex! c lled for complex(self) __oct__(self) A str! c lled for oct(self) __hex__(self) A str! c lled for hex(self) __coerce__(self(ot er) A + lueE c lled for coerce(self(ot er)

__irshift__(self(ot er) B c lled for self ))* ot er

STRINGS
/i$(le ;uoted ?/ello? or dou le-;uoted 7/ello7. 7se tri(le [si$(leNdou le! ;uotes for $ulti-lines strin+s C 777/ello8 how are you F777 /trin+s are i$$uta le =once created a strin+ cannot e $odified in (lace>. /trin+s can contain inary data4 includin+ null chars =chars of code 0>. /trin+s are se;uences4 see 1nde*in+ =(<> for chars inde*ation =slicin+> and other o(erations. chr(code)A strE string of one ch r ord(c ar)A intE code str(expr)A strE re d ble te)tu l represent tion of expr ; if + il ble 8expr8 A strE re d ble te)tu l represent tion of expr ; if + il ble repr(expr)A strE e+ lu ble te)tu l represent tion of expr ; if + il ble >a >b >e >f >n >r >t $scape se+uences ell acks(ace esca(e for$ feed ne- line carria+e return horiAontal ta ># - #ertical ta >? - sin+le ;uote >7 - dou le ;uote >> - ackslash >ooo - char y octal ooo #alue >x - char y he*adeci$al #alue ><newline> - continue strin+ on ne*t line.

?nd for 7nicode strin+s C >uxxxx - unicode char y &Y its he*adeci$al xxxx #alue. >Gxxxxxxxx - unicode char y 92 its he*adeci$al xxxxxxxx #alue. >NHnameI - unicode char y na$e in the 7nicode data ase. ,ee( & esca(e chars y (refi*in+ strin+ literals -ith a r =or D> - for Ora-O strin+s =note C cannot ter$inate a ra- strin+ -ith a &>. ,nicode strings Quoted as for str4 ut -ith a u =or E> (refi* efore the strin+ C u7JoiKi7 G777Gne bonne journLe en perspecti#e:777 Can $i* strin+s (refi*s r =or D> and u =or E>. Eou $ust define your source file encodin+ so that Python kno-s ho- to con#ert your source literal strin+s into internal unicode strin+s. unichr(code) A unicodeE string of one ch r ord(unicode c ar) A intE unicode code unicode(object[(encoding[(errors!!) A unicodeE unicode sys.maxunicode A intE m )imum unicode codeIfctCcompile time optionD /nico!e Chars Infor ations :odule unicodedata contains infor$ations a out 7nicode chars (ro(erties4 na$es. lookup(name) A unicodeE unicode ch r from its n me name(unic r[(default!) A strE unicode n me ; m y r ise Jalue3rror decimal(unic r[(default!) A intE decim l + lue ; m y r ise Jalue3rror digit(unic r[(default!) A intE digit + lue ; m y r ise Jalue3rror numeric(unic r[(default!) A floatE numeric + lue ; m y r ise Jalue3rror category(unic r) A strE gener l unicode c tegory of ch r bidirectional(unic r) A strE bidir c tegory of ch r" m y be empty string combining(unic r) A str& E c nonic l combining cl ss of ch r s integer east_asian_width(unic r) A strE e st si n :idth mirrored(unic r) A intE mirrored property in bidi te)t" 1 if mirrored else 9 decomposition(unic r) A strE decomposition m pping" m y be empty str normali"e=form( unistr) A strE norm l form of string ; form in ?NF.?" ?NF*.?" ?NFA?" ?NF*A? unidata_version A strE +ersion of 2nicode d t b se used "ethods and Functions )ro$ uiltins =see also oct and hex functions for inte+ers to strin+s> C len(s) A intE number of ch rs in the string 5b

BIT LEVEL OPERATIONS


Mork -ith int and long data. Operators :x A in+erted bits of x x3+ A bit:ise e)clusi+e or on x nd + x1+ A bit:ise nd on x nd + x2+ A bit:ise or on x nd + x44n A x shifted left by n bits C4eroes insertedD x))n A x shifted right by n bits C4eroes insertedD .inary structures $ani(ulations in standard $odule struct. ?d#anced inary structures $a((in+ and $ani(ulation in third (arty $odules C ctypes4 xstruct4 pyconstruct4 L (it Le&el O&erri!in' __and__(self(ot er) A + lueE for self 1 ot er __or__(self(ot er) A + lueE for self 2 ot er __xor__(self(ot er) A + lueE for self 3 ot er __lshift__(self(ot er) A + lueE for self 44 ot er __rshift__(self(ot er) A + lueE for self )) ot er __invert__(self) A + lueE for :self __iand__(self(ot er) B c lled for self 1* ot er __ior__(self(ot er) B c lled for self 2* ot er __ixor__(self(ot er) B c lled for self 3* ot er __ilshift__(self(ot er) B c lled for self 44* ot er 5a

:ost strin+ $ethods are also a#aila le as functions in the standard string $odule. s.capitali"e() A string :ith first ch r c pit li4ed1 s.center(widt [(fillc ar!) A string centered s.count(sub[(start[(end!!) A intE count sub occurences s.decode([encoding[(errors!!) A unicodeE te)t decoded ; see encodings Cp12D s.encode([encoding[(errors!!) A strE te)t encoded ; see encodings Cp12D s.endswith(suffix[(start[(end!!) A boolE test te)t ending s.expandtabs([tabsi,e!) A string :ith t bs repl ced by sp ces s.find(sub[(start[(end!!) A int&)1E offset of sub s.index(sub[(start[(end!!) A intE offset of sub ; m y r ise Jalue3rror s.isalnum() A boolE non empty string :ith ll lph numeric ch rs1 s.isalpha() A boolE non empty string :ith ll lph betic ch rs1 s.isdigit() A boolE non empty string :ith ll digit ch rs1 s.islower() A boolE non empty string :ith ll lo:er ch rs1 s.isspace() A boolE non empty string :ith ll sp ce ch rs1 s.istitle() A boolE non empty string :ith titlec se :ords1 s.isupper() A boolE non empty string :ith ll upper ch rs1 s.6oin(se8) A stringE se1K9LOsOse1K1LOsOFOse1Kn;1L s.l6ust(widt [(fillc ar!) A te)t string left ligned2 s.lower() A te)t string lo:ered1 s.lstrip([c ars!) A string te)t :ith le ding c ars2 remo+ed s.replace(old(new[(count!) A string :ith count firsts old repl ced by new s.rfind(sub[(start[(end!!) A int&)1E l st offset of sub s.rindex(sub[(start[end!!)A intE l st offset of sub ; m y r ise Jalue3rror s.r6ust(widt [(fillc ar!) A string te)t right ligned2 s.rsplit([sep[(maxsplit!!)A [string]E rightmost :ords delim. by sep2 s.rstrip([c ars!) A string :ith tr iling ch rs2 remo+ed s.split([sep[(maxsplit!!) A [string]E :ords delimited by sep2 s.splitlines([keepends!) A [string]E list of te)t lines s.startswith(suffix[(start[(end!!) A boolE test te)t begining s.strip([c ars!) A string te)t :ith le dingOtr iling ch rs2 remo+ed s.swapcase() A string :ith c se s:itched1 s.title() A string :ith :ords c pit li4ed1 s.translate(table[(deletec ars!) A stringE cle ned" con+erteds.upper() A string uppered1 s."fill(witd ) A stringE string prefi)ed :ith 4eroes to m tch widt & Locale de(endant for < its strin+s. 2 6efault chars2se(arator2fillchar is s(ace. 9 )or str ta le $ust e a strin+ of 25Y chars - see string.maketrans(). )or 7nicode no deletechars4 and ta le $ust e a $a( of unicode ordinals to unicode ordinals. Formating 7se 0 o(erator et-een for$at strin+ and ar+u$ents C string0args )or$atin+ string contains 0[(name$![flag![widt ![.precision!code 1f not use 0(name)L D args H sin+le #alue or tu(le of #alues. 1f use 0(name)L D args H $a((in+ -ith name as keys. )or $a((in+4 args can e an o 3ect -ith __getitem__ $ethod - see '#erridin+ :a((in+ '(erations =(<>. ,or at char co!es d o x e f g c r si+ned int. deci$al C -4(' unsi+ned octal C ;;' unsi+ned he*a C f4a float. (oint e*(. C )4:(6Ce)1( float. (oint dec. C ) : 4( like e or f character =& char str or code> o 3ect for$at like repr(object) *e plates Mith string.Template o 3ects. 7se co$$on \ synta* C JJ B sin+le \ J Jname or J#name7 B +alue for name. 5c i u F G H I 0 s si+ned int. deci$al C -4(' unsi+ned deci$al CB64 unsi+ned he*a C F41 float. (oint e*(. C )4:(6C3)1( float. (oint dec. C ) : 4( like G or H 00 D 0 o 3ect for$at like str(object)

tmpl * string.Template(template_string) tmpl.substitute(mapping[(++kwargs!> A stringE templ te filled tmpl.safe_substitute(mapping[(++kwargs!) A stringE templ te filled tmpl.template A string Can su class 8e$(late to uild your o-n te$(latin+ =see doc4 sources>. /ee also $odules formatter. 0rappin' :odule textwrap has a Text9rapper class and tool functions. tw = textwrap.@extKrapper([!) A ne: te)t :r pper using n med p r ms s corresponding ttributes + lues tw.width A intE m ) length of :r pped lines Cdef ult 59D tw.expand_tabs A boolE repl ce t bs by text.expandtabs() Cdef ult TrueD tw.replace_whitespace A boolE repl ce e ch :hitesp ce by sp ce Cdef ult TrueD tw.initial_indent A stringE prepend to first :r pped line Cdef ult ??D tw.subse;uent_indent A stringE prepend to other :r pped lines Cdef ult ??D tw.fix_sentence_endings A boolE try to sep r te sentences by t:o sp ces Cdef ult FalseD tw.break_long_words A boolE bre k :ords longer th n :idth Cdef ult TrueD tw.initial_indent A stringE prepend to first :r pped line Cdef ult ??D tw.wrap(text) A [string]E list of te)t lines" e ch :ith m ) :idth length ; no fin l ne:line tw.fill(text) A stringE :hole te)t" lines :r pped using ne:lines 8-o con#enient functions use te$(orary Text9rapper4 uilt usin+ na$ed (ara$eters corres(ondin+ to attri utes. wrap(text[(widt H; [(!!) A [string] fill(text[(widt H; [(!!) A string dedent(text) A stringE remo+e uniform :hitesp ces t beginning of text lines !onstants /tandard $odule string (ro#ide se#eral constants =do not $odify4 they are used in strin+ $ani(ulation functions> and so$e str functions are not a#aila le as $ethods. ascii_letters A strE lo:erc se nd upperc se ch rs ascii_lowercase A strE lo:erc se ;4 ch rs ascii_uppercase A strE upperc se A;V ch rs digits A strE 9;7 decim l digit ch rs hexdigits A strE 9;7 ;fA;F he) decim l digit ch rs letters A strE lo:erc se nd upperc se ch rs1 lowercase A strE lo:erc se ;4 ch rs1 octdigits A strE 9;5 oct l digit ch rs punctuation A strE scii ch rs considered s punctu tion in $ loc le printable A strE print ble ch rs uppercase A strE upperc se A;V ch rs1 whitespace A strE :hitesp ce ch rs Cspc" t b" cr" lf" ff" +tD capwords(s) A strE split A c pit li4e A join maketrans(from(to) A tr nsl tion t ble us ble in str.tr nsl te ; from nd to must h +e s me length 1 6efinition is locale de(endant. egular $&pressions /tandard $odule re has a (o-erfull re+e*( en+ine. /ee re+e*( F'M8' at htt(C22---.a$k.ca2(ython2ho-to2re+e*2. 7se ra- strin+ r77 notation. /ee also e*ternal (ro3ects pyparsing4 PLE =Python Le*-Eacc>4 tpg =8oy Parser Generator>L #$pressions :etacharacters C : M N - 5 F H I < = > O " $4 $ay use > esca(e. : B m tch ny ch r cter e)cept ne:line Cincluding ne:line :ith C>@LMM optionD M B m tch st rt of string C nd st rt of lines :ith ?EM@=M=<G optionD N B m tch end of string C nd end of lines :ith ?EM@=M=<G optionD expr- B m tch 9 or more repetitions of expr C s much s possibleD 6a

expr5 B m tch 1 or more repetitions of expr C s much s possibleD exprF B m tch 9 or 1 expr expr-F B m tch like expr- but s fe: s possible expr5F B m tch like expr5 but s fe: s possible exprFF B m tch like exprF but s fe: s possible exprHmI B m tch m repetitions of expr exprH[m!8[n!I B m tch from m to n repetitions of expr" missing m def ult to 9 nd missing n def ult to infinite exprH[m!8[n!IF B m tch like exprH[m!8[n!I but s fe: s possible <set= B m tch one ch r in the set defined by E M A t begining" in+ert set definition x)+ A ch rs from x to + >x A see 'sc pe se1uences for strings Cp0D >) 4 >= A ch rs ) nd = C) nd = t the beginning m tch ; nd L ch rsD x A ch r x Cincluding other re met ch r ctersD expr9Oexpr: B m tch expr9 or expr:" short p th e+ lu tion "expr$ B m tch expr nd build numbered group "F[i![P![m![s![u![x!$ B C t le st one ot iPmsux ch rD group m tch empty string" modify options fl gs for entire e)pression ; see = M ? A E F options "F!expr$ B m tch expr but dont build group "FQ<name%expr$ B m tch expr nd build group numbered nd n med Cname must be + lid *ython identifierD "FQ=name$ B m tch te)t m tched by e rlier group n med name "F@text$ B no m tch" te)t is just comment "F=expr$ B m tch if m tch expr but donGt consume input "FRexpr$ B m tch if doesnGt m tch expr but donGt consume input "F<=expr$ B m tch if current position is immedi tly preceded by m tch for fi)ed length p ttern expr "F<Rexpr$ B m tch if current position is immedi tly not preceded by m tch for fi)ed length p ttern expr "F"num6name$+esexpr[Onoexpr!$ B try to m tch +esexpr if group num&name e)ists" else try to m tch noexpr #scape Se)uences >n >nn B m tch- group number n CnnD :here first nW9 >ooo > o B m tch- ch r :ith oct l + lue ooo C oD >1 B m tch only t the st rt of the string >b B m tch- empty string t beginning or end of :ord1O2 >S B m tch empty string not t beginning or end of :ord1O2 >d B m tch ch r cl ss decim l digit < )B= >A B m tch ch r cl ss non;digit <M )B= >s B m tch ch r cl ss :hitesp ce < >t>n>r>f>#= >0 B m tch ch r cl ss non;:hitesp ce <M >t>n>r>f>#= >w B m tch ch r cl ss lph numeric <a)z1)T )B,= >9 B m tch ch r cl ss non; lph numeric <Ma)z1)T )B,= >T B m tch end of string >a >b >f >n >r >t ># >x >> B s me s string esc pes >c B for other c ch rs" m tch ch r c
& 2 9

Matchin' an! Searchin' Can use re functions4 or co$(ile e*(ressions into 0E3,Qattern o 3ects and use their $ethods. /ee )la+ '(tions su(ra for flags (ara$eters. search(pattern(string[(flags!)A 2atchUbject&NoneE sc n throught string to find substrings m tching pattern match(pattern(string[(flags!)A 2atchUbject&NoneE try to m tch string :ith pattern split(pattern(string[(maxsplit-.!)A [string]E split string by occurences of pattern ; if maxsplit specified" rem inder is put in l st item of list findall(pattern(string[(flags!)A [string]&[(string)]E find non;o+erl pping substrings m tching pattern ; e+entu lly empty m tchs ; return list of tuples if pattern h s groups finditer(pattern(string[(flags!)A iter tor o+er [2atchUbject] ; s me s findall but :ith n iter tor sub(pattern(repl(string[(count-.!)A stringE repl ce substrings m tching pattern by repl ; repl s string c n cont in b ck references1 to identified substring ; repl s fctC2atchUbjectD return repl cement string ; p ttern m y be E3,Qattern object subn(pattern(repl(string[(count-.!)A (string(int)E s me s sub" 2nd item is count of substitutions escape(string)A stringE non; lph numerics b cksl shed 1f you need to reuse a (attern4 co$(ile it one ti$e for all. pat * re.compile(pattern[(flags!)A E3,Qattern object pat.match(string[(pos[4endpos!!) A s me s match function2 pat.search(string[(pos[4endpos!!) A s me s search function2 pat.split(string[(maxsplit-.!)A s me s split function2 pat.findall(string[(pos[(endpos!!)A s me s findall function2 pat.finditer(string[(pos[(endpos!!)A s me s finditer function2 pat.sub(repl(string[(count-.!)A s me s sub function pat.subn(pattern(repl(string[(count-.!)A s me s subn function pat.flags A intE fl gs used t compile time pat.pattern A stringE p ttern used t compile time pat.groupindex A dictE m pping of group n mes to group numbers /e#eral functions2$ethods return 2atchUbject o 3ects. m.expand(template)A stringE do b cksl sh substitution on template Clike sub methodD using m tch object groups + lues m.group([group[(!!)A string&(string)E subgroups of the m tch from numbers or n mes m.groups([default-&one!)A (string)E ll subgroups of the m tch ; default gi+e ccess to subgroups not in the m tch m.groupdict([default-&one!)A dictE n meAsubgroupE ll n med subgroups of the m tch ; default gi+e ccess to subgroups not in the m tch m.start([group-.!)A intE inde) of st rt of substring m tched by group" )1 if group e)ists but not in m tch m.end([group-.!)A intE inde) of end of substring m tched by group" )1 if group e)ists but not in m tch m.span([group-.!)A (intS2T)E + lues of st rt nd end methods for the group m.pos A intE pos + lue of se rch&m tch method m.endpos A intE endpos + lue of se rch&m tch method m.lastindex A int&NoneE inde) of l st m tched c pturing group m.lastgroup A string&NoneE n me of l st m tched c pturng group m.re A E3,QatternE p ttern used to produce m tch object m.string A stringE string used in m tch&se rch to produce m tch object
& &

6e(ends on 751C'6" fla+. 6e(ends on L'C?L" fla+. Mhen out of char class definition =<=> ,la' Options

=I<>DGNLAG ==> C case insensiti#e e*(ression - not locale de(endant. M>NLMG =M> C $ake >w >9 >b >S locale de(endant. ?EM@=M=<G =?> C ^ and $ $atch e+inin+2end of strin+ and lines. "lse M and N $atch only e+innin+ and end of strin+. C>@LMM =A> C $ake : $atch any char includin+ ne-line. "lse ne-line e*cluded. E<=N>CG =E> C $ake >w >9 >b >S unicode de(endant. OGDP>AG =F> C i+nore -hites(aces and $ake @ startin+ co$$ents =e*ce(t -hen s(ace and @ are esca(ed or in char class>.

.ack references e*tended to >g<groupnum% and >g<groupname%. 7sin+ (art of strin+ et-een pos and endpos. Grou( nu$ er 0 corres(ond to entire $atchin+. %ocali-ation /tandard $odule locale (ro#ide (osi* locale ser#ice =internationaliAation>. setlocale(categor+[(locale!) A current&ne: settingsE if locale specified C s string or s tupleCl ngu ge code" encodingDD then modify loc le settings for 6c

6b

c tegory nd return ne: one ; if locale not specified or None" return current loc le ; not thre d s fe localeconv()A dictE d t b se of loc l con+entions nl_langinfo(option)A stringE loc le;specific inform tions ; not + il ble on ll systems ; options m y + ry on systems ; see options p5 getdefaultlocale([envvars!)A(l ngu ge code( encoding)E try to determine def ult loc le settings getlocale([categor+!)A current P.,- setting for c tegory ; c tegory def ult to P.,.TVQ3 ; for l ngu ge code nd ncoding it m y be None getpreferredencoding([do_setlocale!)A strE user preffered encoding for te)t d t ; set do_setlocale to False to +oid possible c ll to setlocale() normali"e(localename)A norm li4ed loc le code for localename ; us ble :ith setlocale"# ; return localename if norm li4 tion f ils resetlocale([categor+!) B reset loc le for c tegory to def ult setting ; c tegory def ult to MN_LMM strcoll(s14s2)A intE comp re t:o strings ; follo: MN_N>MML@G setting ; return 9 if s1IIs2" H9 if s1Hs2" J9 if s1Js2 strxfrm(string)A stringEtr nsform string for loc le; : re comp rison format=format(val[(grouping!)A stringEcon+ert + l flo t using form t CX oper tor con+entionsD ; follo: MN_<E?GD=N settings Cdecim l point" O grouping if it is trueD str(float)A stringE con+ert flo t ; follo: MN_<E?GD=N settings Cdecim l pointD atof(string)A floatE con+ert string to flo t ; follo: MN_<E?GD=N settings atoi(string)A intE con+ert string to integer ; follo: MN_<E?GD=N settings NQLD_?LF A symbolic const nt used by localeconv() Cate'ories MN_N@RSG A ch r cter type ; c se ch nge beh +iour MN_N>MML@G A strings sorting ; strcoll() nd strxfrm() functions MN_@=?G A time form ting ; time.strftime() MN_?><G@LDR A monet ry + lues form ting ; options from localeconv() MN_?GAALIGA A mess ges displ y ; os.strerror() ; not for *ython mess ges MN_<E?GD=N A numbers form tting ; format()" atoi()" atof() nd str() of this module Cdont modify norm l *ython number form tingD MN_LMM A ll loc les ; used to ch nge&retrie+e the loc le for ll c tegories nl1lan'info options
/)y n(0(&n1-n2o34 +&(%) %,&1)

/)y

n(0(&n1-n2o34 +&(%) %,&1)

GDL_C_H?@ LM@_C=I=@A
/)y

usa le as for$at for strftime() for date -ith era u( to &00 #alues re(resentin+ 0 to @@
$)&n-n1

localecon& +eys currency,symbol decimal,point frac,digits grouping Local currency sy$ ol for $on)t&5y #alues. 6eci$al (oint character for n%$')5,. 5u$ er of fractional di+its used in local for$attin+ of $on)t&5y #alues. [int]C relati#e (ositions of OthousandsUse(O in n%$')5,. NQLD_?LF at the end sto( +rou(in+. at the end re(eat last +rou(. 1nternational currency sy$ ol of $on)t&5y #alues. 5u$ er of fractional di+its used in international for$attin+ of $on)t&5y #alues. 6eci$al (oint used for $on)t&5y #alues. ";ui#alent to O+rou(in+O4 used for $on)t&5y #alues. Grou( se(arator used for $on)t&5y #alues. 8rue if currency sy$ ol (receed ne+ati#e $on)t&5y #alues4 false if it follo-. 8rue if there is a s(ace et-een currency sy$ ol and ne+ati#e $on)t&5y #alue. Position of ne+ati#e si+n for $on)t&5y #alues&. /y$ ol used to annotate a ne+ati#e $on)t&5y #alue. 8rue if currency sy$ ol (receed (ositi#e $on)t&5y #alues4 false if it follo-. 8rue if there is a s(ace et-een currency sy$ ol and (ositi#e $on)t&5y #alue. Position of (ositi#e si+n for $on)t&5y #alues&. /y$ ol used to annotate a (ositi#e $on)t&5y #alue. Character used et-een +rou(s of di+its in n%$')5,.

lngettext(singular(plural(n)A stringE like ngettext()" using preferred encoding dngettext(domain(singular(plural(n)A stringE like ngettext()" looking in specified dom in. ldngettext(domain(singular(plural(n)A stringE like dngettext()" using preferred encoding Generally _ is ound to gettext.gettext4 and translata le strin+s are -ritten in sources usin+ _(?thestring?). /ee docs for usa+e e*a$(les. Class base! A"I 8he reco$$ended -ay. :odule gettext defines a class Translations4 dealin+ -ith .$o translation files and su((ortin+ str2unicode strin+s. find(domain[(localedir[(languages[(all!!!)A str&NoneE .mo file n me for tr nsl tions Cse rch in loc ledir&l ngu ge&($Y%'SSA@'S&dom in.moD translation(domain[(localedir[(languages[(class_[(fallback[(codeset!!!!!) ATranslationsE object from cl ss cl ssY Cdef ult to WNGTranslations" constructor t ke file object s p r meterD ; if true f llb ck llo: to return NullTranslations if no .mo file is found" def ult to f lse Cr ise +U3rrorD ; codeset ch nge ch rset used to encode tr nsl ted strings install(domain[(localedir[(unicode[(codeset!!!) B inst ll _ function in *ythonGs builtin n mesp ce" to use _(?thestring?) .ull *ranslations 8he NullTranslations is a ase class for all 8ranslations. t.__init__([fp!) B initi li4e tr nsl tionsE fp is file object ; c ll _parse(fp) if it is not None t._parse(fp) B nothingE subcl sses o+erride to re d d t from the file t.add_fallback(fallback) B dd f llb ck used if c nnot found tr nsl tion for mess ge 6efine $ethods gettext4 lgettext4 ngettext4 lngettext as in the ase ?P1. ?nd define s(eciale $ethods ugettext and ungettext returnin+ unicode strin+s =other for$s return encoded str strin+s>. Return translated $essa+e4 for-ardin+ to fall ack if it is defined. '#erriden in su classes. t.info()A return protected _info ttribute t.charset()A return protected _charset ttribute t.output_charset()A return protected _output_charset ttribute Cdefining encoding used to return tr nsl ted mess gesD t.set_output_charset(c arset) B set _output_charset ttribute t.install([unicode!) B bind _ in builtin n mesp ce to self.gettext() or self.ugettext() upon unicode Cdef ult to f lseD G./ *ranslations 8he WNGTranslations class =su class of NullTranslations> is ased on G57 +ette*t and .$o files. :essa+es ids and te*ts are coerced to unicode. Protected _info attri ute contains $essa+e translations. 8ranslation for e$(ty strin+ return $eta-data =see doc>. 6efine $ethods gettext4 lgettext4 ugettext4 ngettext4 lngettext4 ungettext as in NullTranslations interface - sa$e rules for return #alues =str2unicode>. :essa+e translations are searched in catalo+4 then in fall ack if defined4 and if no translation is found4 $essa+e itself is returned =for n* $ethods4 return sin+ular for$s if nH1 else (lural for$s>.

int,curr,symbol int,frac,digits mon,decimal,point mon,grouping mon,thousands,sep n_cs_precedes n_sep_by_space n,sign,posn negati#e,sign p_cs_precedes p_sep_by_space p,sign,posn positi#e,sign thousands,sep
&

N>CGAG@ C_@_H?@ C_H?@ @_H?@ @_H?@_L?S? CLR_ LCLR_T LPCLR_ L LPCLR_T ?><_ L ?><_ ! LP?><_ L LP?><_ ! DLC=FNQLD @Q>EAGS RGAGFSD <>GFSD ND<NRA@D

na$e of character encodin+ usa le as for$at for strftime() for ti$e and date usa le as for$at for strftime() for date usa le as for$at for strftime() for ti$e usa le as for$at for strftime() for ti$e in a$2($ for$at na$e of the nth day of the -eek - first day is sunday a re#iated na$e of the nth day of the -eek - first day is sunday na$e of the nth $onth a re#iated na$e of the nth $onth radi* character =deci$al dot2co$$a2L> se(arator character for thousands re+ular e*(ression =of C li raryR> usa le for yes re(ly re+ular e*(ression =of C li raryR> usa le for no re(ly currency sy$ ol4 (receded y ) if should a((ear efore the #alue4 y 5 if should a((ear after the #alue4 y : if should re(lace radi* character era - +enerally not defined - sa$e as 3 for$at in strftime() year in era usa le as for$at for strftime() for date and ti$e -ith era 7a

Possi le #alues C Hcurrency and #alue surrounded y (arentheses4 1Hsi+n should (recede #alue and currency sy$ ol4 (Hsi+n should follo- #alue and currency sy$ ol4 4Hsi+n should i$$ediately (recede #alue4 'Hsi+n should i$$ediately follo- #alue4 MN_?LFHnothin+ s(ecified in this locale. "ultilingual Support /tandard $odule gettext for internationaliAation =1&<5> and localiAation =L&05> ser#ices - ased on G57 +ette*t ?P1 [ hi+her interface. /ee docs for e*(lanations a out tools usa+e. (ase A"I bindtextdomain(domain[(localedir!)A strE bounded directory ; bind dom in to loc ledir directory if specified Cused :hen se rching for .mo filesD bind_textdomain_codeset(domain[(codeset!)A codeset bindingE bind dom in to codeset if specified ; ch nge ))gette)tCD returned strings encoding textdomain([domain!)A glob l dom inE set glob l dom in if specified nd not None gettext(message)A stringE loc li4ed tr nsl tion of mess ge ; b sed on current glob l dom in" l ngu ge" nd loc le directory ; usu lly li sed s Y in loc l n mesp ce lgettext(message)A stringE like gettext()" using preferred encoding dgettext(domain(message)A stringE like gettext()" looking in specified dom in. ldgettext(domain(message)A stringE like dgettext()" using preferred encoding ngettext(singular(plural(n)A stringE like gettext()" but consider plur l forms Csee *ython nd @!2 gette)t docsD 7b

CONTAINERS
.asic containers kind C -,)6%)n7), =ordered collections> C list4 tuple4str4 any itera le4L -$&pp-n1, =unordered key2#alue> C dictL -,)t, =unordered collections> C set4 frozensetL Operations on !ontainers )or strin+s4 ite$s are chars. )or $a((in+s4 ite$s are keys. item in container A boolE test item Z container1 item not in container A boolE test item [ container1 7c

GDL GDL_RGLD GDL_C_@_H?@

for var in container: L B iter te var o+er items of container len(container) A intE count number of items in container2 max(container) A + lueE biggest item in container min(container) A + lueE sm llest item in container sum(container) A + lueE sum of items Citems must be number;comp tibleD & )or strin+s test if e*(r is a su strin+ of se;uence. 2 Container $ust (ro#ide direct len+th $ethod - no +enerator. !opying !ontainers 6efault containers constructors uild ne- container -ith references to e*istin+ o 3ects =shallo- co(y>. 8o du(licate content too4 use standard $odule copy. /ee Co(yin+ ' 3ects =(9>. O(erriding !ontainers Operations __len__(self)A intE c lled for len(self) __contains__(self(item)A boolE c lled for item [not! in self Eou can o#erride itera le (rotocol on containers too.

-t)$, -n.)9, -n 0 e& 0 -n & -n[& Slice objects 6efines inde* ran+e o 3ects4 usa le in [] notation. slice([start(!stop[(step!)A slice object slice.indices(len)A (intS-T)E Cst rt"stop"strideD 'rdered sets of data inde*ed fro$ 0. :e$ ers start4 stop4 step. #$ten!e! Slicin' :ulti(le slices notation - corres(ondin+ to a selection in a $ultidi$ension data - can e -ritten usin+ notation like [ a , x:y:z , : , : , : , m:n ]. "lli(sis notation can e used to fill $ulti(le $issin+ slices4 like [ a , x:y:z , ... , m:n ]. /ee docs. 8hree dot notation ... is re(laced internally y 3llipsis o 3ect. Operations on mutable se+uences :uta le se;uences =e*. list> can e $odified in (lace. Can use $uta le se;uence inde*in+ in left (art of assi+n$ent to $odify its ite$s C se8[index]*expr J se8[start:stop]*expr J se8[start:stop:step]*expr se8.append(item) B dd item t end of se1uence se8.extend(ot erse8) B conc ten te otherse1 t end of se1uence se8.count(expr) A intE number of e)pr items in se1uence se8.index(expr[(start[(stop!!)A intE first inde) of e)pr item se8.insert(index(item) B item inserted t inde) se8.remove(expr) B remo+e first e)pr item from se1uence se8.pop([index!) A itemE remo+e nd return item t inde) Cdef ult ;1D se8.reverse() B items re+ersed in pl ce se8.sort([cmp![(key![(reverse!) B items sorted in pl ce ; cmp E custom comp rison fctC "bD" ret+ l H9 or I 9 or J9 ; key E n me of items ttribute to comp re ; reverse E bool del se8[index] B remo+e item from se1uence del se8[start:stop[:step!] B remo+e items from se1uence O(erriding Se+uences Operations __getitem__(self(index2)A + lueE item t index" c lled for self[index] __setitem__ (self(index2(value) B set item t index to value" c lled for self[index]*value __delitem__ (self(index2) B remo+e item t index" c lled for del self[index] & 'nly for $uta le se;uences. 2 Para$eter inde* can e a slice [start4sto(4ste(! - re(lace old UU+etsliceUU4 UUsetsliceUU4 UUdelsliceUU. Can also o#erride arith$etic o(erations __add__ =concatenation > and __mul__ =re(etition >4 container o(erations and o 3ect o(erations. -n[& & e2 2 -n[2 -n[2 2 e9 9 -n[9 L L *-t)$* L L n-2 -2 -2 n-2 en-& n-& -& -& n-& en n

,(-7-n1 -n.)9,

SE8UENCES
/e;uences are ordered collections C str4 unicode4 list4 tuple4 buffer4 xrange4 array.arrayL any user class definin+ se;uences interface4 or any itera le data. %ists * Tuples .uiltin ty(es list and tuple store se;uences of any o 3ects. Lists are $uta le4 tu(les are i$$uta le. 6eclare a list C [item[(L!] 6eclare a tu(le C (item[(L!) 5otes C [] B e$(ty list J() B e$(ty tu(le J (item() B one ite$ tu(le. list(object) A listE ne: list Cc st from object & duplic te e)istingD tuple(object) A tupleE ne: tuple Cc st from object & duplic te e)istingD range([start(!stop[(step!)A [int]E list" rithmetic progression of integers xrange ([start(!stop[(step!) A xrangeE object gener ting rithmetic progression of integers 7nless usin+ a se;uence as a $a((in+ key4 or ensurin+ it is i$$uta le data4 (refer list to tuple. & 7se in (lace of ran+e to a#oid uildin+ hu+e lists 3ust for inde*in+. Operations on Se+uences /ee '(erations on Containers =(7> too. se81 - se82 A conc ten tion of se81 nd se82 se8uence + n A conc ten tion of se8uence duplic ted n times n + se8uence A conc ten tion of se8uence duplic ted n times reversed(se8uence)A iter tor throught se8uence in re+erse order sorted(se8uence[(cmp[(ke+[(reverse!!!)A listE ne: list" sorted items from iter ble ; see list.sorted() filter (fct4se8uence)A listE ne: list :here fctCitemD is True. 2se None fct for boole n test on items map (fct(se8uence(L)A listE ne: list :here ith item is fctCith items of se8uence"s#D reduce(fct(se8uence[(initiali,er!)A + lueE fct pplied cumul ti+ely to se1uence items" fCfCFfCfCfCiniti li4er" D"bD"c"FD "ip (se8uence4L)A listE list of tuples" ith tuple cont ins ith items of e ch se1uences
&

Operations on "appings /ee '(erations on Containers =(7> too4 considerin+ o(erations on keys. d[ke+]A + lue for ke+1 d[ke+]*value B set d[ke+] to value del d[ke+] B remo+es d[ke+] from d1 d.fromkeys(iterable[(value-None!) A dictE :ith keys from iterable nd ll s me + lue d.clear() B remo+es ll items from d d.copy() A dictE h llo: copy of d d.has_key(k)A boolE test key presence ; s me s k in d d.items()A listE copy of dGs list of Ckey" itemD p irs d.keys()A listE copy of dGs list of keys d.update(ot erd) B copy ot erd p irs into d d.update(iterable) B copy Ckey"+ lueD p irs into d d.update(++kwargs) B copy n meI+ lue p irs into d d.values()A listE copy of dGs list of + lues d.get(ke+(defval)A + lueE d[ke+] if ke+Zd" else defval d.setdefault(ke+[(defval-None!) A + lueE if ke+[d set dKke+]*defval" return d[ke+] d.iteritems()A iter tor o+er Ckey" + lueD p irs d.iterkeys()A iter tor o+er keys d.itervalues()A iter tor o+er + lues d.pop(ke+[(defval!) A + lueE del ke+ nd returns the corresponding + lue. If ke+ is not found" defval is returned if gi+en" other:ise *ey3rror is r ised d.popitem() A remo+es nd returns n rbitr ry Ckey" + lueD p ir from d & 1f key doesnOt e*ist4 raise *ey3rror e*ce(tion. O(erriding "apping Operations __getitem__(self(ke+)A + lue for ke+" c lled for self[ke+] __setitem__(self(ke+(value) B set + lue for ke+" c lled for self[ke+]*value __delitem__(self(ke+(value) B remo+e + lue for key" c lled for del self[ke+] Can also o#erride container o(erations and o 3ect o(erations. Other "appings )or on-disk $a((in+s4 see standard $odule shelve4 and data ase $odules . )or ordered $a((in+s see third (arty $odules >rderedCict.

SETS
7nordered collections of uni;ue ite$s. )roAen sets are i$$uta le once created. set([iterable!) A setE using + lues from iterable fro"enset([iterable!) A frozensetE using + lues from iterable Operations on Sets /ee '(erations on Containers =(7> too. s.issubset(ot ers)A boolE test s \ ot ers s.issuperset(ot ers)A boolE test ot ers \ s s.add(item) B dd item to set s.remove(item) B remo+e item from set1 s.clear() B emo+es ll items from Cnot for4enD set s.intersection(ot ers)A setE s ] ot ers s 1 ot ers A setE s ] ot ers s.union(ot ers) A setE s ^ ot ers s 2 ot ers A setE s ^ ot ers s.difference(ot ers) A setE K) & )Zs nd )[ot ersL s . ot ers A setE K) & )Zs nd )[ot ersL s.symmetric_difference(ot ers)A setE K) & )Zs )or )Zot ersL s 3 ot ers A setE K) & )Zs )or )Zot ersL s.copy()A setE sh llo: copy of s s.update(iterable) B dds ll + lues from iterable to s & Raise ,ey"rror if o 3ect not in set. Results set ha#e sa$e ty(e as s o 3ect =set2frozenset>. 8c

/ee 1teration 8ools =(@> as re(lace$ent =a#oid creatin+ a ne- list>.

Inde&ing 7se inde* [i] and slice [i:j[:step!] synta*. 1nde*s Aero- ased. 5e+ati#e inde*s inde*in+ fro$ end. 6efault ste( is 14 can use ne+ati#e ste(s. /u -se;uences inde*s et-een ite$s. l = <e18e(8e48X8en)(8en)18en= l< = e1 l< !n=<e18e(8e48X8en)(8en)18en= l<1= e( l<!=<e18e(8e48X8en)(8en)18en= l<)(= en)1 l<i!=<ei518ei5(8ei548X8en)18en= l<)1= en l<!i=<e18e(8X8ei)(8ei)18ei=

MAPPINGS 3DICTIONARIES4
.uiltin ty(e dict. /tore keyC#alue (airs. 6eclare a dictionary C # ke+:value [(L!7 #7 dict()A dictE empty diction ry Clike STD dict(++kwargs)A dictE from n med p r meters nd their + lues dict(iterable)A dictE from Ckey"+ lueD by iter ble dict(ot erdict)A dictE duplic ted fro nother one Cfirst le+elD

8a

8b

OTHER CONTAINERS STRUCTURES# ALGORITHMS


Generally containers follo- Python idio$s4 you can use C len(cont)4 cont[i]4 for item in cont:L Array /tandard $odule array (ro#ides efficient array of asic ty(es. 1t uses co$(act stora+e for ele$ents of sa$e ty(e. *ype Co!es
n t7 C typ) py typ) n t7 C py typ)

eap" push newitem nlargest(n(iterable)A listE n l rgest from iterable nsmallest(n(iterable)A listE n sm llest items from iterable Sorted %ist /tandard $odule bisect $aintains lists sorted =#ia asic isection al+o>. bisect_left(list(item[(lo[( i!!)A intE inde) to insert item t leftmost sorted position1 bisect_right(list(item[(lo[( i!!)A intE inde) to insert item t rightmost sorted position1 bisect(L) B li s for bisect_right(L) insort_left(list(item[(lo[( i!!) B insert item t leftmost sorted position1 insort_right(list(item[(lo[( i!!) B insert item t rightmost sorted position1 insort(L) B li s for insort_right(L) & Mith list (re#iously sorted. Iteration Tools /tandard $odule itertools (ro#ides so$e (ractical iterators. chain(iterable[(L!)A iter tor o+er items of se+er l iter bles count([start!)A iter tor o+er integers from st rt Cdef ult 9D cycle(iterable)A iter tor cycling o+er iterable items dropwhile(predicatefct(iterable)A iter tor o+er items of iterable :here predicatefctCitemD is f lse groupby(iterable[(ke+fct!)A iter tor o+er Ckey + lue"group1 of items :here ke+fctCitemDIkey + lueD" def ult ke+fct is identity ifilter(predicate(iterable)A iter tor o+er items of iterable :here predicatefctCitemD is true ; None predic te filter items being true ifilterfalse(predicate(iterable)A iter tor o+er items of iterable :here predicatefctCitemD is f lse ; None predic te filter items being f lse imap(function(iterable[(L])A iter tor o+er functionCitems t s me inde) from iterables2D" None function return tuples items islice=iterable([start(!stop[(step!)A iter tor o+er items t slice- inde)s from iterable" !one stop goes up to end i"ip(iterable[(L])A iter tor o+er tupleCitems t s me inde) from iter blesD repeat(object[(count!)A iter tor returning object o+er nd o+er g in" up to count times Cdef ult to infiniteD starmap(function(iterable)A iter tor o+er functionCRtuple item from iter bleD takewhile(predicatefct(iterable)A iter tor o+er items of iter ble :here predic tefctCitemD is true tee(iterable[(n!) A n independent iter tors from s me iter ble/" def ult nI2 & Grou( of ite$s is internally used - $ust sa#e it as list if needed after current iteration. 2 /to( at end of shorter itera le. 9 /lice (ara$eters cannot e ne+ati#e. 4 6onOt use itera le out of tee created iterators.

accept!dyear A Kr:L boolE ccept t:o;digit ye r + lues Cdef ult trueD" modifi ble +i en+ironment + r *_T>O!_2` alt"one A intE offset Cpos&negD in seconds of ,ST rel ti+ely to 2T$" in seconds" use only if d ylight is true daylight A intE W9 if ,ST time4one is defined time"one A intE offset Cpos&negD in seconds of loc l Cnon ,STD time4one t"name A (strS2T)E n mes of loc l time4one Cnon;,ST" ,STD ,unctions asctime([t-2!)A strE build loc l time string from t CtupleYtime or structYtimeD clock()A floatE processor time in seconds" for ccur te rel ti+e time me surement ctime([secs-2!)A strE build loc l time string from flo tYtime second gmtime([secs-2!)A struct,timeE con+ert flo tYtime to 2T$ structYtime localtime([secs-2!)A struct,timeE con+ert flo tYtime to ,ST structYtime mktime(t)A float,timeE con+ert ,ST t CtupleYtime or structYtimeD to flo tYtime ; m y r ise U#erflow3rror or Jalue3rror sleep(secs) B e)ecution suspended during secs Cflo tYdel yD times" m ybe less Csign l c tchingD" m y be more Cprocess&thre ds schedulingD strftime(format[(t-2!) A strE build time string from t CtupleYtime or structYtimeD using format string Ct ble infr D ; m y r ise Jalue3rror strptime(string[(format!) A struct,timeE p rse string using time format1 ; m y r ise Jalue3rror time() A flo tYtimeE current 2T$ time t"set() B resets time con+ersion rules ccordingly to en+ironnment + ri ble TV ; uni) only" see docs
&

& & 2 2 4 4

?b? ?c? ?h? ?i? ?l? ?f?

si+ned char si+ned si+ned si+ned float

char short int lon+

int str int int int float

& 2 2 2 4 <

?S? ?u? ?/? ?+? ?P? ?d?

unsi+ned char unicode char unsi+ned short unsi+ned int unsi+ned lon+ dou le

int unicode int long long float

nHsiAe in ytes4 tcHchar ty(ecode to use ,unctions array(tc4[iterable!) A arrayE :ith typecode tc" initi li4ed from iterable a.typecode A strE typecode of a d t a.itemsi"e A intE bytes si4e of a d t a.append(expr) B ppend item expr to end of a a.extend(arra+) B ppend items from nother arra+ a.count(expr) A intE number of expr items a.index(expr) A intE first inde) of expr item a.insert(index(expr) B expr item inserted t index a.remove(expr) B remo+e first expr item a.pop([index!) A + lueE return nd remo+e item t index Cdef ult ;1D a.reverse() B items in rr y re re+ersed a.buffer_info() A (intS2T)E current stor ge infos C ddress"items countD a.byteswap() B s: p bytes of rr y items a.fromfile(f(n) B ppend n items re d from re l bin ry file f1 a.tofile(f) B :rite ll items to re l bin ry file f a.fromlist(list) B e)tend rr y from + lues in list a.tolist() A listE items in list a.fromstring(s) B e)tend rr y from + lues in bin ry buffer s CstringD a.tostring() A strE items in bin ry represent tion a.fromunicode(s) B e)tend GuG rr y from d t in unicode stirng a.tounicode() A unicodeE con+ert GuG rr y to unicode string & 1f less ite$s than needed4 +et a#aila le ones then raise 3UF3rror. 'ld $ethods read and -rite re(laced y fro$file and tofile. .ueue /tandard $odule collections (ro#ides ;ueues $ana+e$ent. de;ue([iterable!)A deYueE initi li4ed from iterable 8.append(x) B dd x to right side of de1ue 8.appendleft(x) B dd x to left side of de1ue 8.clear() B remo+e ll elements from de1ue 8.extend(iterable) B e)tend right side of de1ue :ith iterable items 8.extendleft(iterable) B e)tend left side of the de1ue :ith iterable items 8.pop() A itemE pop nd return item from de1ueue right side 8.popleft() A itemE pop nd return item from de1ueue left side 8.rotate(n) B rot te de1ue from n steps" to right if nJ9" to left if nH9 Can also use standard o(erations on se;uences C len(8)( reversed(8)( copy.copy(8)4 copy.deepcopy(8)4 item in 84 8[)1]4 and serialiAation #ia (icklin+ (rotocol. 'riority .ueues /tandard $odule heap;. /tructure a list as a (riority ;ueue. heapify(x) B tr nsform list x into he p heappush( eap(item) B push item onto eap heappop( eap)A itemE pop nd return sm llest item from the eap heapreplace( eap(newitem)A itemE pop nd return sm llest item from the 9a

6efault for$at P]a ] ]d ]FC]:C]/ ]EP. :issin+ #alues default to =&@004 &4 &4 04 04 04 04 &4 -&> 2 Para$ secs default to current ti$e4 (ara$ t default to local current ti$e. *i e for at strin's Za Zb Zc Z/ Zj Z2 Z0 Zw Zx Zy ZT
&

? ?

re#iated -eekday na$e&. re#iated $onth na$e&.

?((ro(riate date and ti$e re(resentation&. Four [00429!. Eear day [00&49YY!.

Z1 ZS Zd

)ull -eekday na$e&. )ull $onth na$e&. :onth day [0&49&!. Four [0&4&2!. :onth [0&4&2!. ?: or P:&. Eear -eek [00459! =/unday ased>. Eear -eek [00459! =:onday ased>. ?((ro(riate ti$e re(resentation&. Eear =-ith century>. Literal ] char.

Z+ Zm :inute [0045@!. Zp /econd [004Y&!. ZG Meek day [04Y! =0H/unday>. Z9 ?((ro(riate date re(resentation&. Z[ Eear [004@@!. ZV 8i$e Aone na$e =no characters if ZZ
no ti$e Aone e*ists>.

DATE

TIME

Locale lan+ua+e re(resentation.

"odule time /tandard $odule time defines co$$on functions and data. 2ate 3 *i e 2ata 4 float1ti e 5 float containin+ seconds fro$ Oe(ochO =3anuary & &@70 on 7ni* - see gmtime( )>4 -ith su -second (recision in deci$al (art. 4 tuple1ti e H tuple containin+ @ int =see ta le>. 4 struct,time H tuple2o 3ect -ith int attri utes =see ta le>.
: 0 & 2 9 4 &tt5-'%t) +&(%)

"odule datetime /tandard $odule datetime has tools for date2ti$e arith$etics4 data e*traction and $ani(ulation. 6efines class C timedelta4 time4 date4 datetime4 [tzinfo!. "odule timeit /tandard $odule timeit has functions to $easure (rocessin+ ti$e of code. 1t can e used in scri(ts =see docs>4 or directly in co$$and line C python -$t-$)-t [-n &! [-r &! [-s ;! [-t! [-c! [-h! [statement [L!! -n & 2 --nu$ erH& e*ecute statement & ti$es -r & 2 --re(eatH& re(eat ti$er & ti$es =default 9> -s ; 2 --setu(H; e*ecuted ; once initially =default pass> -t 2 --ti$e use time.time() =default e*ce(t Mindo-s> -c 2 --clock use time.clock() =default on Mindo-s> -# 2 --#er ose (rint ra- ti$in+ results - $ay re(eat o(tion -h 2 --hel( (rint hel( and e*it 9c

tm_year tm_mon tm_mday tm_hour tm_min

int 1L1( 1L41 L(4 L6B

: 5 Y 7 <

&tt5-'%t)

+&(%) LC1 LC =$ondayH > L4CC =no> 1 =yes> )1 =unkno-n>

tm_sec tm_wday tm_yday tm_isdst

4 float1!elay 5 float containin+ seconds4 -ith su -second (recision. 6/8 is local ti$e4 78C is uni#ersal =G:8> ti$e. 9b

Other "odules /tandard $odule calendar has functions to uild calendars. /ee also third (arty $odule mxCate@ime.

fsync(fd) B force lo: le+el OS buffers to be :ritten ftruncate(fd(lengt ) B trunc te file descriptor to t most length C2ni)D Open ,la's Constants defined in os $odule4 use it--ise 'R =x y z> to $i* the$. >_DC><MR A re d only >_KD><MR A :rite only >_DCKD A re d&:rite >_LSSG<C A ppend e ch :rite to end >_NDGL@ A cre te ne: file Cremo+e e)istingD >_GFNM A :ith >_NDGL@" f il if file e)ist C2ni)D >_@DE<N A reset e)isting file to 4ero si4e >_CAR<N A )))))) C2ni)D >_DAR<N A )))))) C2ni)D >_AR<N A return from IO :hen d t re physic lly :ritten C2ni)D >_<CGMLR A return immedi tly CdonGt block c ller during IOD C2ni)D >_<><PM>NU A s me s >_<CGMLR C2ni)D >_<>N@@R A termin l de+ice file c nGt become process tty C2ni)D >_P=<LDR A donGt process end of lines CcfOlf from&to crD C<indo:sD >_<>=<QGD=@ A )))))) C<indo:sD >_AQ>D@_M=OGC A )))))) C<indo:sD >_@G?S>DLDR A )))))) C<indo:sD >_DL<C>? A )))))) C<indo:sD >_AGVEG<@=LM A )))))) C<indo:sD >_@GF@ A )))))) C<indo:sD 'ipes )or standard (rocess redirection usin+ (i(es4 see also /i$(le "*ternal Process Control =(&4>. os.pipe() A ((intS2T)S2T)E cre te p ir Cfdm ster"fdsl +D of fd Cre d":riteD for pipe os.mkfifo(pat [(mode-.===!) B cre te n med pipe pat ; mode m sked out :ith um sk ; donGt open it C2ni)D 7se os functions on file descri(tors. In0memory Files Me ory (uffer ,iles 7se standard $odules Atring=> and cAtring=> to uild file-like o 3ects storin+ data in $e$ory. f * Atring=>.0tring+U() .uild a file-like in $e$ory. f.write(string) B d t :ritten to file f.Fother file :riting methodsF f.getvalue() A strE current d t :ritten to file f.close() B file no longer us ble" free buffer c/trin+1' is a co$(iled =$ore efficient> #ersion of /trin+1' for -ritin+. '(tional ar+u$ent allo-s to uild $e$ory files to read fro$ too. f * cAtring=>.0tring+U([string!) f.read([si,e!) A strE block of d t re d from GfileG CstringD f.Fother file re ding methodsF Me ory Mappe! ,iles 6OS le&el7 /tandard $odule mmap $ana+e $e$ory-$a((ed files4 usa le as file-like o 3ects and as $uta le strin+-like o 3ects. 8o uild a $e$ory $a( C mm * mmap.mmap(fileno(lengt [(tagname[(access!!) K:indo:sL mm * mmap.mmap(fileno(lengt [(flags[(prot[(access!!!) Kuni)L 7se an os file descri(tor =fro$ os.open() or fro$ file-o 3ectOs fileno()> for a file o(ened for u(date. Len+th s(ecify a$ount of ytes to $a(. 'n -indo-s4 file $ay e e*tended to that len+th if it is shorter4 it canOt e e$(ty4 and 0 corres(ond to $a*i$u$ len+th for the file. ?ccess =key-ord (ara$> C LNNGAA_DGLC =readonly>4 LNNGAA_KD=@G =-rite-throu+h4 default on Mindo-s>4 or LNNGAA_N>SR =co(y-on--rite>. 10b

FILES
5or$al file o(erations use Python file o 3ects =or file-like o 3ects -ith sa$e interface>. /o$e functions directly $ani(ulate files (ath na$es =strin+s>. )unctions $a((in+ lo- le#el '/ handlers =$ainly those in standard os $odule> use nu$eric file descri(tors =fd also kno-n as fileno>. Ra- data use str ty(e =can contain any data yte #alues4 includin+ 0>. File Objects /tandard file ty(e is uiltin file. 1t defines the Python file (rotocol. Create a file C file(filename[(mode-?r?[(bufsi,e!!) A file object :ode fla+s =co$ ina le> C ?r? read4 ?w? -rite ne-4 ?a? -rite a((end4 ?5? u(date4 ?b? inary&4 ?G? uni#ersal ne-line2. .uffer siAe C un uffered4 1 line uffered4 W& around that siAe. '(en=> is an alias for file=> & 6efault te*t $ode tries to inter(ret ne-line se;uences in the file. 2 ?uto$atically choose ne-line se;uence in CR or L) or CR[L) ada(ted fro$ file2to (latfor$. Metho!s an! ,unctions f.close() B file flushed nd no longer us ble f.fileno() A intE lo: le+el file descriptor CfdD f.flush() B buffers :ritten to file on disk f.isatty() A boolE indic tor file is termin l f.read([si,e!) A strE block of d t re d from file f.readline() A strE ne)t line re d from file" end of line remo+ed f.readlines() A [string]E list of ll lines re d from file" end of lines remo+ed f.seek(offset[(w ence* !) B modify current position in file ; w enceE from st rt" 1 from current" ( from end f.tell() A intE current position in file f.write(string) B d t :ritten to file f.writelines(listofstrings) B d t :ritten to file Cno end of line ddedD for line in f :L B iter te line o+er lines of f 'ld $ethod xreadlines re(laced y iteration on file o 3ect. )or o(ti$iAed direct access to rando$ lines in te*t files4 see $odule linecache. Attributes f.closed A boolE indic tor file h s been closed f.encoding A str&NoneE file content encoding f.name A strE n me of the file f.newlines A str&tuple of str&NoneE encountered ne:lines ch rs f.softspace A boolE indic tor to use soft sp ce :ith print in file %o/0le(el Files .ase lo--le#el functions are in standard $odule os. Careful of clash -ith uiltins -ith os.open na$e. open(pat (flags[(mode-.<<<!)A int CfdDE open file pat ; see flags infr ; mode m sked out :ith um sk fdopen(fd[(mode[(bufsi,e!!) A fileE build file connected to fd ; mode nd bufsi,e s for builtin open()O mode must st rt :ith r or w or a dup(fd)A int CfdDE duplic te file descriptor fd dup!(fd(fd2)A int CfdDE duplic te file descriptor fd into fd2" pre+iously closing fd2 if necess ry close(fd) B close file descriptor read(fd(n)A strE re d s most n bytes from fd file ; return empty string if end of file re ched write(fd(str)A intE :rite str to fd file ; return number of bytes ctu lly :ritten lseek(fd(pos( ow) B set file descriptor position ; owE from st rt" 1 from current" ( from end fdatasync(fd) B flush file d t to disk ; donGt force upd te met d t C2ni)D 10a

'n Mindo-s4 ta+na$e allo- to identify different $a((in+s a+ainst sa$e file =default to 5one>. 'n 7ni*4 fla+s C ?LS_SD=OL@G =co(y-on--rite (ri#ate to (rocess> or ?LS_AQLDGC =default>. ?nd (rot =$e$ory (rotection $ask> C SD>@_DGLC or SD>@_KD=@G4 default is SD>@_DGLC2SD>@_KD=@G. 1f use (rot[fla+s (ara$s4 donOt use access (ara$. mm.close() B mm p file no longer us ble mm.find(string[(start- !)A intE offset & )1 mm.flush([offset(si,e!) B :rite ch nges to disk mm.move(dest(src(count) B copy d t in file mm.read([si,e!)A strE block of d t re d from mm p file1 mm.read_byte()A strE ne)t one byte from mm p file1 mm.readline()A strE ne)t line re d from file" end of line is not remo+ed1 mm.resi"e(newsi,e) B :rit ble mm p file resi4er mm.seek(offset[(w ence* !) B modify current position in mm p file ; w enceE from st rt" 1 from current" ( from end mm.si"e()A intE length of the re l os file mm.tell() A intE current position in mm p file mm.write(string) B d t :ritten to mm pfile1 mm.write_byte(b+te) B str of one ch r CbyteD d t :ritten to mm p file1
&

)ile-like $ethods use and $o#e file seek (osition.

Files Informations )unctions to set2+et files infor$ations are in os and in os.path $odule4 so$e in shutil $odule. Constants fla+s are defined in standard stat $odule. /o$e functions accessin+ (rocess en#iron$ent data =e*. current -orkin+ directory> are docu$ented in Process section. os.access(pat (mode)A boolE test for pat ccess :ith mode using re l uid&gid ; mode in H_>U" D_>U" K_>U" F_>U os.H_>U A ccess mode to test p th e)istence os.D_>U A ccess mode to test p th re d ble os.K_>U A ccess mode to test p th :rit ble os.F_>U A ccess mode to test p th e)ecut ble os.chmod(pat (mode) B ch nge mode of pat ; mode use stat.A_+ const nts os.chown(pat ( uid( gid) B ch nge pat o:ner nd group C2ni)D os.lchown(pat ( uid( gid) B ch nge p th o:ner nd group ; donGt follo: symlinksC2ni)D os.fstat(fd)A intE st tus for file descriptor os.fstatvfs(fd)A stat#fs,resultE inform tions bout file system cont ining file descriptor C2ni)D os.stat(pat )A st t structure objectE file system inform tions C2ni)D os.lstat(pat )A st t structure objectE file system inform tions C2ni)D ; dont follo: symlinks os.stat_float_times([newvalue!)A boolE test&set stat function time st mps d t type ; +oid setting ne: + lue os.statvfs(pat )A stat#fs,resultE inform tions bout file system cont ining p th C2ni)D os.utime(pat (times) B set ccess nd modific tion times of file p th ; timesIC time"mtimeD CnumbersD ; timesINone use current time os.fpathconf(fd(name) A str & intE system configur tion inform tion bout file referenced by file descriptor ; see pl tform document tion nd pathconf_names + ri ble ; n me str or int C2ni)D os.pathconf(pat (name)A str & intE system configur tion inform tion bout file referenced by file descriptor ; see pl tform document tion nd pathconf_names + ri ble ; n me str or int C2ni)D os.pathconf_names A dictE n me A inde) ; n mes ccepted by pathconf nd fpathconf A corresponding inde) on host C2ni)D os.path.exists(pat )A boolE test e)isting p th ; no broken symlinks os.path.lexists(pat )A boolE test e)isting p th ; llo: broken symlinks os.path.getatime(pat )A flo tYtimeE l st ccess time of p th os.path.getmtime(pat )A flo tYtimeE l st modific tion time of p th os.path.getctime(pat )A flo tYtimeE cre tion time C:indo:sD or l st 10c

modific tion time Cuni)D of p th os.path.getsi"e(pat )A intE bytes si4e of p th file os.path.isabs(pat )A boolE test bsolute os.path.isfile(pat )A boolE test regul r file Cfollo: symlinksD os.path.isdir(pat )A boolE test e)isting directory Cfollo: symlinksD os.path.islink(pat )A boolE test symlink os.path.ismount(pat )A boolE test mount point os.path.samefile(pat 1(pat 2)A boolE test refer to s me re l file Cuni)"m cosD os.path.sameopenfile(f1(f2)A boolE test opened files refer to s me re l file Cuni)"m cosD os.path.samestat(stat1(stat2)D boolE test st t tuples refer to s me file "unix1macos# shutil.copymode(srcpat (dstpat ) B copy norm l file permission bits shutil.copystat(srcpat (dstpat ) B copy norm l file permission bits nd l st ccess nd modific tion times Stat Structures stat,result is returned y stat and lstat functions4 usa le as a tu(le and as o 3ect -ith attri utes C
: 0 & 2 9 4 5 Y 7 < @ &tt5-'%t) %,&1) (rotection its inode nu$ er de#ice nu$ er of hard links user 16 of o-ner +rou( 16 of o-ner siAe of file4 in ytes ti$e of $ost recent access ti$e of $ost recent content $odification ti$e of $ost recent $etadata chan+e on 7ni*4 ti$e of creation on Mindo-s nu$ er of locks allocated for file =7ni*> filesyste$ locksiAe =7ni*> ty(e of de#ice if an inode de#ice =7ni*> siAe of resource fork4 in ytes=:ac'/> file creator code =:ac'/> file ty(e code =:ac'/>

A_=DEAD A 99/99 user c n re d A_=KEAD A 99299 user c n :rite A_=FEAD A 99199 user c n e)ecute A_=DKFI A 99959 group c n re dO:riteOe)ecute A_=DIDS A 999/9 group c n re d A_=KIDS A 99929 group c n :rite A_=FIDS A 99919 group c n e)ecute A_=DKF> A 99995 e+erybody c n re dO:riteOe)ecute A_=D>@Q A 9999/ e+erybody c n re d A_=K>@Q A 99992 e+erybody c n :rite A_=F>@Q A 99991 e+erybody c n e)ecute Terminal Operations os.openpty()A (intS2T)E open pseudo;termin l1 p ir Cfdm ster"fdsl +eDICpty"ttyD C2ni)D os.ttyname(fd)A strE termin l de+ice ssoci ted to fd C2ni)D os.isatty(fd)A boolE test file descriptor is tty;like C2ni)D os.tcsetpgrp(fd(pg) B set process group id ssocited :ith termin l fd C2ni)D os.tcgetpgrp(fd)A intE process group ssoci ted :ith termin l fd C2ni)D /ee also standard $odules tty and pty. )or user-interface control on te*t ter$inal 4 see standard (acka+e curses and its su -$odules. Temporary Files 7se standard tempfile $odule. 1t defines se#eral functions to $ake life easier and $ore secure. @emporaryHile=[mode-$w0b$[(bufsi,e-31[(suffix[(prefix[(dir!!!!!) A file&file;likeE temp file ; remo+ed on close ; not necess ry +isible in file;system ; dir nd prefix s for mkstemp <amed@emporaryHile=[mode-$w0b$[(bufsi,e-31[(suffix[(prefix[(dir!!!!!) A file&file;likeE like @emporaryHile ; file +isible in file;system mkstemp([suffix[(prefix[(dir[(text!!!!)A (int(str)E Cfd"p thD of ne: tempor ty file ; no r ce condition ; only cre tor c n re d&:rite ; no e)ecut ble bit ; not utom tic lly deleted ; bin ry mode unless te)t specified mkdtemp([suffix[(prefix[(dir!!!)A strE p th of ne: tempor ry directory cre ted ; no r ce condition ; only cre tor c n re d&:rite&se rch ; not utom tic lly deleted gettempdir() A strE def ult directory for tempor ry files gettempprefix() A strE def ult filen me prefi) for tempor ry files 'ther functions in tempfile and os $odules are ke(t for code co$(ati ility4 ut are considered not enou+h secured. ?lso tempdir and template data in tempfile - -hich should not e used directly. 'ath "anipulations Path $ani(ulation functions are in standard os.path $odule. supports_unicode_filenames A boolE unicode us ble for file n mes abspath(pat )A strE norm li4ed bsoluti4ed p thn me basename(pat )A strE file n me p rt of pat commonprefix(pat list) A strE longest common p th prefi) Cch r;by;ch rD dirname(pat )A strE directory n me of p thn me 6oin(pat [(L!)A strE conc ten te p th components normcase(pat )A strE norm li4e p th c se for pl tform Csee docD normpath(pat )A strE norm li4e p th C&& &.& &..&D" on :indo:s &A a realpath(pat )A strE c nonic l p th Cremo+e symlinksD Cuni)D split(pat )A (strS2T)E split into Che d" l st p thn me componentD splitdrive(pat )A (strS2T)E split into Cdri+e" t ilD splitext(pat )A (strS2T)E split into Croot" e)tD Host Specific "ath 2ata sys.getfilesystemencoding() A strE n me of encoding used by system for filen mes )ollo-in+ data are in os and in os.path. curdir A strE string used to refer to current directory pardir A strE string used to refer to p rent directory sep A strE ch r used to sep r te p thn me components 11b

altsep A strE ltern ti+e ch r used to sep r te p thn me components extsep A strE ch r used to sep r te b se filen me from e)tension pathsep A strE con+ention l ch r to sep r te different p ths )irectories os.listdir(pat )A [str]&[unicode]E list n mes in pat directory ; :ithout : nd :: ; rbitr ry order ; p th string type A item strings type os.mkdir(pat [(mode-.<<<!) B cre te directory pat ; mode m sked out :ith um sk os.makedirs(pat [(mode-.<<<!) B cre te directory pat " recursi+ely ; mode m sked out :ith um sk ; donGt h ndle <indo:sG 2!$ p th os.rmdir(pat ) B remo+e directory p th os.removedirs(pat ) B remo+e directories" recursi+ely os.walk(top[(topdown-True [(onerror-&one!!)A iter bleE go throught dirs under top" for e ch dir yield tupleCdirp th" dirn mes" filen mesD ; onerrorIfctCos.errorD ; see docs os.path.walk(pat (visit(arg) B c ll visitCarg"dirn me"n mesD for dirs rooted t pat ; m y modify n mes Cfiles listD to influence : lk" m y prefer to use os.walk Special Files os.link(src(dst) B cre te h rd link n med dst referencing src C2ni)D os.symlink(src(dst) B cre te symbolic link n med dst pointing to src C2ni)D os.readlink(pat )A strE pat pointed to by symbolic link os.mknod(pat [(mode-.===(device!) B cre te FS node Cfile" de+ice speci l file" n med pipeD ; mode I permissions M nodetype ; node type in A_=HDGI" A_=HDGI" A_=HNQD" A_=HPMU" nd A_=H=H> defined in stat module os.ma6or(device) A intE r : de+ice m jor number os.minor(device) D intC ra- de#ice $inor nu$ er os.makedev(major(minor) B compose r : de+ice from m jor nd minor numbers !opying, "o(ing, emo(ing os.remove(pat ) B remo+e file pat Cnot directoryD os.rename(src(dst) B ren me src to dst ; on s me filesystem; m y remo+e e)isting dst file os.renames(old(new) B ren me old to new" recursi+ely ; try to cre te intermedi te directories os.unlink(pat ) B remo+e file pat Cnot directoryD ; s me s remove /tandard $odule shutil (ro#ides hi+h le#el functions on files and directories. copyfile(src(dst) B copy norm l file content ; o+er:rite destin tion2. copyfileob6(fsrc(fdst[(lengt -1=kb!) B copy file;like object content by blocks of length si4e CH9Ione chunkD copy(src(dst) B copy norm l file content to file&directory2 ; in c se of directory use s me b sen me s src ; o+er:rite destin tion ; copy permission bits. copy!(src(dst) B s me s copy O copy l st ccess nd modific tion times2. copytree(src(dst[(s+mlinks-False!) B recursi+ely copy directory tree ; destin tion must be ne: ; files copied +i copy ; if s+mlinks is F lse" copy symbolic links files content" else just m ke symbolic links.1 rmtree(pat [(ignore_errorsHFalse[(onerrorHNone!!) B recursi+ely delete directory tree ; onerrorIfctCfctref" p th" e)cinfoD.1 move(src(dst) B recursi+ely mo+e file or directory tree ; m y ren me or copy.1
& 2

st_mode st_ino st_dev st_nlink st_uid st_gid st_si"e st_atime st_mtime st_ctime st_blocks st_blksi"e st_rdev st_rsi"e st_creator st_type

stat#fs,result is returned y fstatvfsand statvfs functions4 usa le as a tu(le =use statvfs #aria le inde*s> and as an o 3ect -ith attri utes C
: 0 & 2 9 4 5 Y 7 < @ &tt5-'%t) -n.)9 +&5

f_bsi"e f_frsi"e f_blocks f_bfree f_bavail f_files f_ffree f_favail f_flag f_namemax

H_PA=WG H_HDA=WG H_PM>NUA H_PHDGG H_PLOL=M H_H=MGA H_HHDGG H_HLOL=M H_HMLI H_<L?G?LF

%,&1) (referred file syste$ lock siAe funda$ental file syste$ lock siAe total nu$ er of locks in the filesyste$ total nu$ er of free locks free locks a#aila le to non-su(er user total nu$ er of file nodes total nu$ er of free file nodes free nodes a#aila le to non-su(er user fla+s - see host stat#fs=> $an (a+e $a*i$u$ file na$e len+th

Stat Constants 6efined in standard stat $odule. A_=AE=C A ))))) A_=AI=C A ))))) A_G<H?@ A ))))) A_=AO@F A ))))) A_=DGLC A 99/99 user c n re d A_=KD=@G A 99299 user c n :rite A_=GFGN A 99199 user c n e)ecute A_=DKFE A 99599 user c n re dO:riteOe)ecute 11a

:ay raise shutil.3rror e*ce(tion. Para$s src and dst are files (ath na$es.

$ncoded Files /tandard $odule codecs ha#e functions and o 3ects to trans(arently (rocess encoded files =used internally as unicode files>. codecs.open(filename(mode[(encoding[(errors[(buffering!!!)A file;like 3ncodedFile object :ith tr nsp rent encoding&decoding codecs.GncodedHile(file(input[(output[(errors!!) A file;like :r pper round file" decode from input encoding nd encode to output encoding codecs.P>? A strE li s for P>?_E@H X codecs.P>?_PG A strE li s for P>?_E@H X_PG 11c

codecs.P>?_MG A strE li s for P>?_E@H X_MG codecs.P>?_E@HY A strE ?>xef>xbb>xbf? codecs.P>?_E@H X A strE li s for P>?_E@H X_MG or P>?_E@H X_PG codecs.P>?_E@H X_PG A strE ?>xfe>xff? codecs.P>?_E@H X_MG A strE ?>xff>xfe? codecs.P>?_E@HZ! A strE li s for P>?_E@HZ!_MG or P>?_E@HZ!_PG codecs.P>?_E@HZ!_PG A strE ?>x >x >xfe>xff? codecs.P>?_E@HZ!_MG A strE %&xff&xfe&xBB&xBB% /ee "ncodin+ - 6ecodin+ =(&2> for details a out encoding and errors. Seriali-ation /tandard $odules pickle and cSickle =s(eed u( to &000*> ha#e su((ort for data serialiAation of o 3ects hierarchies. /ee Python docu$entation. /ee also $odule marshal =read2-rite of Python data in (latfor$ inde(endant inary for$at - ut can roke for$at et-een releases>. 'ersistence /tandard $odule shelve use (icklin+ (rotocol to store o 3ects in 6.: files =see (&7> and access the$ #ia a dictionnary-like interface -ith keys as str. open(filename[(flag[(protocol[(writeback[(binar+!!!!)A diction ry;like object ; flag s anydbm.open Cp15D" def ult to GcG ; protocol def ult to 9 C scii form tD ; writebackE c che ccessed entries in memory nd :ritten them b ck t close time" def ult to F lse ; binar+ is deprec ted" use protocol. !onfiguration Files /tandard $odule NonfigSarser. 1t uses standard .!"! files to store confi+udation data C <section= %alues can contain Z"name$s references -hich name!#alue $ay e e*(anded usin+ #alues in sa$e section or name=#alue in defaults @ and \ start co$$ent lines. :odule defines 9 confi+uration classes -ith different data access le#el C Eaw.onfigQarser .onfigQarser 0afe.onfigQarser rp*DawNonfigSarser([defaults!) A Eaw.onfigQarser cp*NonfigSarser([defaults!) A .onfigQarser sp*AafeNonfigSarser([defaults!) A 0afe.onfigQarser 1n the three constructors4 defaults is a dict of o(tionC#alue for references e*(ansion. ?LF_=<@GDS>ML@=><_CGS@Q A intE m ) recursi+e depth for getCD :hen r : p r meter is f lse CGHLEM@AGN@ A strE n me of def ut section -aw Interface rp.defaults()A dictE def ult + lues for references e)p nsion rp.sections()A [string]E list sections in config C:ithout ,'FA2(TD rp.add_section(section> B dd ne: section ; m y r ise Auplicate0ection3rror rp.has_section(section)A boolE test if section e)ists ; c nt test for ,'FA2(T rp.options(section)A [string]E list options in section rp.has_option(section(option)A boolE test if section nd option e)ists rp.read([filename]6filename)A [filen me]E try to lo d configur tion d t from files Ccontinue if f ilD ; return n mes of lo ded files rp.readfp(fp[(filename!) B lo d configur tion d t from file&file;like rp.get(section(option)A strE option + lue rp.getint(section(option)A intE coerce option + lue to int rp.getfloat(section(option)A floatE coerce option + lue to flo t rp.getboolean(section(option)A boolE coerce option + lue to bool ; True is strings 1 yes true on ; False is strings no false off ; m y r ise Jalue3rror rp.items(section)A[(n me(+ lue)]E options in the section rp.set(section(option(value) B set option to string + lue in section ; m y r ise No0ection3rror 12a

rp.write(fileobject) B :rite configur tion d t to file rp.remove_option(section(option)A boolE return True if there : s such option ; m y r ise No0ection3rror rp.remove_section(section)A boolE return True if there : s such section rp.optionxform(option)A strE norm li4ed intern l form of option .or al Interface cp.get(section(option[(raw[(vars!!)A stringE + lue for option in section ; X interpol tion e)p nded unless raw is true ; vars is dict of ddition l def ults ; reference e)p nsion n mes re processed by optionxform() for m tching cp.items(section[(raw[(vars!!)A [(n me(+ lue)]E for gi+en section ; raw nd vars s in get() Safe Interface sp.set(section4option4value) B set + lue string for section nd option #$ceptions =3xception> 3rror Qarsing3rror No0ection3rror Auplicate0ection3rror 2issing0ection/eader3rror NoUption3rror +nterpolation3rror +nterpolationAepth3rror +nterpolation2issingUption3rror +nterpolation0yntax3rror )or si$ilar file for$at su((ortin+ nested su sections4 see Nonfig>b6 confi+ (arser. )or -indo-s users4 standard $odule _winreg. )or te*t-file confi+s4 can use B:L tools4 and see also third (arty E?:L (arsers like SyRaml.

Euntime3rror ^ =(refer definin+ ad-hoc su classes>. Not+mplemented3rror 0yntax3rror +ndentation3rror Tab3rror 0ystem3rror ^ a u+L in Python. Type3rror Jalue3rror ^ +ood ty(e4 ut ad #alue. Gnicode3rror 9arning ^ -arnin+s su(erclass =see Marnin+s infra> Gser9arning QendingAeprecation9arning Aeprecation9arning 0yntax9arning Euntime9arning 1arnings Marnin+s $ust e su classes of 9arning root class. /tandard warnings $odule control (rocessin+ of -arnin+ e*ce(tions. 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[4append!!!!!) resetwarnings() sys.warnoptions $&ceptions 'rocessing sys.exc_info()A (type(+ lue(tr ceb ck) for current e)ception1 sys.exc_clear() B current e)ception rel ted inform tions cle red sys.excepthook A Cr:D fctCtype" + lue" tr ceb ckD c lled for unc ught e)ceptions sys.__excepthook__ A b ckup of origin l e)cepthook function sys.tracebacklimit A intE Cr:D m )imum le+els of tr ceb ck printed" HI9 for none & 'r =5one45one45one> if no runnin+ e*ce(tion. /tandard $odule traceback has tools to (rocess and for$at these infor$ations.

EXCEPTIONS
/tandard e*ce(tions defined in exceptions $odule4 and a#aila le in current sco(e. ?ll e*ce(tions $ust e su classes of 3xception root class. 7se standard e*ce(tions if their $eanin+ corres(ond to you errors. /u class standard e*ce(tions -hen needed. Standard $&ception !lasses 3xception 0top+teration ^ iteratorOs ne*t=>4 no $ore #alue. 0ystem3xit ^ sys.e*it=> called 0tandard3rror ^ uilt-in e*ce(tions 1rithmetic3rror ^ arith$etic errors. FloatingQoint3rror U#erflow3rror TeroAi#ision3rror 1ssertion3rror ^ assert cond[(message! failed. 1ttribute3rror ^ attri ute set2+et failed. 3n#ironment3rror ^ host syste$ error - see ar+ tu(le attri ute +U3rror U03rror 9indows3rror ^ Mindo-s error codes. 3UF3rror ^ end-of-file -ith input() or raw_input(). +mport3rror *eyboard+nterrupt ^ user interru(t =Ctrl-C>. Pookup3rror +ndex3rror ^ non-e*istent se;uence inde*. *ey3rror ^ non-e*istent $a((in+ key. 2emory3rror Name3rror ^ non-e*istent na$e in current sco(e. GnboundPocal3rror ^ reference to an unassi+ned local #aria le. Eeference3rror ^ try accessin+ -eak-ref dis(osed o 3ect. 12b

ENCODING - DECODING
/tandard $odule codecs (ro#ide ase su((ort for encodin+ 2 decodin+ data. 8his is used for character encodin+s4 ut also for data co$(ression =Ai(4 A2> or data re(resentation =uu4 he*>. /ee 7nicode strin+s =(5>4 /ource encodin+s =(9>. /ee functions4 classes and constants for files encodin+ in "ncoded )iles =(&&>. :odule encodings.aliases.

THREADS

SYNCHRONI;ATION

Python threads use nati#e threads. ? +lo al $ute* =the G1L> lock inter(reter data durin+ Python #irtual instructions e*ecution =it is unlocked durin+ 12' or lon+ co$(utation in nati#e code>. Check for thread s-itchin+ and si+nal (rocessin+ is (erfor$ed at re+ular inter#al. sys.getcheckinterval()A intE current thre d s:itching check inter+ l1 sys.setcheckinterval(interval) B set hre d s:itching check inter+ l1
&

"*(ressed in nu$ er of Python #irtual instructions.

Threading Functions 7se standard hi+h le#el $odule threading -hich (ro#ides se#eral classes C Thread4 local =for thread local stora+e>4 3#ent4 Pock and EPock =$ute*>4 0emaphore and Souded0emaphore4 Timer. :odule threading also (ro#ides functions C activeNount()A intE number of currently cti+e thre ds current@hread()A ThreadE current running thre d enumerate()A [Thread]E list of cti+e thre ds 12c

settrace(func) B inst ll tr ce function c lled before thre ds run methods setprofile(func) B inst ll profile function c lled before thre ds run methods /tandard $odule thread su((orts lo- le#el thread $ana+e$ent. 7se $odules dummy_thread and dummy_threading on (latfor$s -ithout $ultithreadin+. Threads Class threading.Thread is used to create ne- e*ecution (ath in current (rocess. 1t $ust e called -ith key-ord ar+u$ents. /(ecify thread code -ith a calla le target (ara$ or y o#erridin+ run $ethod =re$e$ er callin+ inherited __init__ in su classes>4 +i#e ar+u$ents in args and kwargs =tu(le and dict>4 +i#e a name to identify the thread - group currently not used =5one>. t * threading.@hread(group(target(name(args(kwargs) t .start() B st rt thre d cti+ity Cin nother thre dD t .run() B thre d code to e)ecute ; c ll t rget if not o+erriden t .6oin([timeout!) B : it for th termin tion or timeout el psed Cflo tYdel y" def ult to None for infiniteD t .get<ame()A strE thre d ssoci ted n me t .set<ame(name) B set thre d ssoci ted n me Ciniti l n me set by cl ssD t .isLlive()A boolE test thre d li+e Cst rted nd runCD not termin tedD t .isCaemon()A boolE test thre d h +e d emon fl g t .setCaemon(daemonic) B set thre d d emon fl g ; must be c lled before st rt. Initi l fl g inherited from cre ting thre d. *ython process e)it only fter l st non;d emon thre d termin tion. ? thread canOt e killed or (aused e*ternally y another thread. *hrea! Local Stora'e Class threading.local attri utes #alues are thread local. /u class it or use it as a na$es(ace. tlsdata = threading:local"$ tlsdata:x = 1 2elaye! Start *hrea! Class threading.Timer is a su class of Thread -hich effecti#ely run after a s(ecified inter#al fro$ its start. t * threading.@imer(interval(function(args*[](kwargs*#7) t.cancel() B timer :ill ne+er run ; must not be lre dy running Create a ti$er that -ill run function -ith ar+u$ents ar+s and key-ord ar+u$ents k-ar+s4 after inter#al seconds ha#e (assed. "utual $&clusion Classes threading.Pock and threading.EPock (ro#ide $utual e*clusion et-een threads. Pock doesnOt allo- a thread to re-ac;uire a lock it already o-ns4 EPock does =reentrant-lock>. lock * threading.Mock() lock * threading.DMock() lock.ac;uire([blocking!)A bool&NoneE c1uire the lock. blocking unspecified E : it . return None b blocking true E : it . return True b blocking f lse E donGt : it CtryD . return True&False lock.release() B unlock pre+iously c1uired lock :ust release a lock sa$e ti$es as it -as ac;uired. Good (ractice to ac;uire2release locks in try2finally locks. )or (orta le inter-(rocess $ute*4 see third (arty glock.py $odule. $(ents Class threading.3#ent is a synchronisation fla+ -ith thread lockin+ $echanis$ to -ait for the fla+. evt * threading.Gvent() B ne: e+ent" :ith intern l fl g set to F lse evt.isAet()A boolE + lue of e+ent intern l fl g evt.set() B set e+ent intern l fl g to true ; unlock : iting thre ds evt.clear() B set e+ent intern l fl g to F lse evt.wait([timeout!) B : it for e+ent intern l fl g to be true ; timeout is flo tYdel y Cdef ult to NoneIinfinite blockingD

General purpose e&ents sche!uler %odule sched pro+ides such tool" d pt ble to your needs CGtimeG unit is yoursD. sc * sched.scheduler(timefunc(dela+func) A schedulerE timefunc return numbers mesuring time" dela+funcCnD : it n time Cs me unit s timefunc outputD ; typic lly sc * sched.scheduler(time.time(time.sleep) sc.enterabs(time(priorit+(action(args) A e+tidE schedule ne: e+ent" :ill c ll action(+args) t time sc.enter(dela+(priorit+(action(args)A e+tidE schedule ne: e+ent" :ill c ll action(+args) fter dela+ sc.cancel(evtid)B remo+e scheduled e+ent ; m y r ise Euntime3rror sc.empty()A boolE test if scheduler e+ents 1ueue is empty sc.run()B run scheduled e+ents t their scheduling time ; see docs Semaphores Classes threading.0emaphore and threading.Sounded0emaphore (ro#ide si$(le se$a(hore for resources countin+ =-ithout2-ith counter checkin+>. sem * threading.Aemaphore([value-1!) B sem phore :ith initi l counter sem * threading.PoundedAemaphore([value!) sem.ac;uire([blocking!)A bool&NoneE c1uire the sem phore Cconsume one resourceD. blocking unspecified E : it . return None b blocking true E : it . return True b blocking f lse E donGt : it CtryD . return True&False sem.release() B rele se the sem phore Cfree one resourceD !ondition 2ariables Class threading..ondition allo-s threads to share state =data> (rotected #ia a Pock. 1$(ortant C condition #aria les =lock> $%,t e ac;uired -hen callin+ wait4 notify or notifyLll. /ee Python docs. cond * threading.Nondition([lock!) B build ne: condition + ri ble" use user pro+iden lock CPock or EPockD else build ne: EPock cond.ac;uire(+args)A + lueE c1uire cond. + r. lock" return lock. c1uireCD + lue cond.release() B rele se cond. + r. lock cond.wait([timeout!) B : it until notified or timeout el psed; timeout is flo tYdel y Cdef ult to !oneIinfinite blockingD. #ele se cond. + r. lock nd : it for notific tion&timeout then re; c1uire lock. cond.notify() B : ke up one : iting thre d Cif nyD. cond.notifyLll() B : ke up ll : iting thre ds. Synchroni-ed .ueues :odule Vueue (ro#ides a class ]ueue to store data in a synchroniAed )1)' ;ueue4 and t-o e*ce(tion classes Full and 3mpty. 1n lockin+ $ode4 full ;ueue lock (roducers and e$(ty ;ueue lock consu$ers =in non- lockin+ $ode they raise e*ce(tions>. 'ther or+aniAation can e uilt -ith su classin+ =see source for internal $ethods>. 8 * ;ueue.Vueue(maxsi,e) B build ne: 1ueue ; infinite 1ueue if m )si4eHI9 8.;si"e()A intE si4e of the 1ueue ; t c ll time 8.empty()A boolE test if 1ueue si4e if 9 ; t c ll time 8.full()A boolE test if 1ueue si4e is m )si4e ; t c ll time 8.put(item[(block[(timeout!!) B put item in 1ueue ; block c n be true&f lse" timeout c n be None&flo tYdel y. % y r ise Vueue.Hull e)ception. 8.put_nowait(item) B s me s put(item(False) 8.get([block[(timeout!!)A itemE remo+ed from 1ueue ; block c n be true&f lse" timeout c n be None&flo tYdel y ; m y r ise Vueue.Gmpty e)ception 8.get_nowait() B s me s get(False)

sys.exit([arg-.!) B e)it +i 0ystem3xit e)ception Cm y be c tchD ; rg is e)it code os._exit(n) B e)it :ithout cle nup os.abort() B e)it +i SI@AB#T sign l Csign l m y be h ndledD )ollo-in+ e*it codes are defined in os =7ni*> C GF_>U no error GF_EALIG co$$and used incorrectly GF_CL@LGDD incorrect in(ut data GF_<>=<SE@ una#aila le2inaccessi le in(ut GF_<>EAGD unkno-n user GF_<>Q>A@ unkno-n host GF_E<LOL=MLPMG re;uired ser#ice una#aila le GF_A>H@KLDG internal error GF_>AGDD '/ error GF_>AH=MG $issin+2inaccessi le file GF_NL<@NDGL@ canOt create out(ut GF_=>GDD error durin+ file 12' GF_@G?SHL=M te$(orary failure GF_SD>@>N>M ille+al2in#alid2not understood (rotocol e*chan+e GF_<>SGD? not enou+h (er$issions =out of file (er$s> GF_N><H=I confi+uration (ro le$ GF_<>@H>E<C $issin+ data Eou can install e*it functions =for nor$al e*it> -ith $odule atexit. register=func[4Sargs[4SSkargs!!> B register function to be c lled :ith rgs nd k rgs Re+istered functions are called in re#erse order of re+istration. .y(assed -hen (rocess is ter$inated y a si+nal4 an internal error4 or an os._exit. #n&iron ent 8ariables environ A dictE en+ironment + ri bles ; modific tion c ll putenv if supported getenv(varname[(defaultHNone!)A strE en+ironment + ri ble + lue putenv(varname(value) B set en+ironment + ri ble ; ffect l ter st rted subprocess ; m y c use memory le ks Csee pl tform document tionD /o$e functions also in os.path C expanduser(pat )A strE p th :ith initi l cdc or cduserc repl ced expandvars(string)A strE string :ith Nname or NHnameI en+ironment + ri ble repl ced 2irectory9 ,iles9 *er inal /ee also Console 0 1nteracti#e 1n(ut2'ut(ut =(&>4 and )iles - 8er$inal '(erations =(&&>. chdir(pat ) B ch nge current :orking directory to pat fchdir(fd) B ch nge current :orking directory to thus represented by file descriptor getcwd()A strE current :orking directory getcwdu()A unicodeE current :orking directory chroot(pat ) > c ange process file3s+stem root to pat "?nix# umask(mask)A intE set current numeric um sk nd return pre+ious one ctermid()D strE filen me of controlling termin l C2ni)D getlogin()A strE n me of user logged on controlling termin l C2ni)D /ser9 process9 'roup I2s pidC (rocess id4 gidC +rou( id4 uidC user id getpid()A intE current pid getegid()A intE effecti+e gid C2ni)D setegid(egid) B set process effecti+e gid C2ni)D geteuid()A intE effecti+e uid C2ni)D seteuid(euid) B set process effecti+e uid C2ni)D getgid()A intE re l gid C2ni)D setgid(gid) B set process gid C2ni)D getuid()A intE current processG uid C2ni)D setuid(uid) B set process current uid C2ni)D 13c

PROCESS
!urrent 'rocess /tandard $odule os has tools to +et infor$ation a out and $ani(ulate current (rocess and its en#iron$ent. #$itin' 5or$ally Python (rocess e*it -hen there is no $ore non-dae$on thread runnin+. 13b

13a

setregid(rgid(egid) B set process re l nd effecti+e gid C2ni)D setreuid(ruid(euid) B set process re l nd effecti+e uid C2ni)D getpgrp()A intE current gid C2ni)D getgroups()A [int]E list of supplement l ssoci ted gid C2ni)D setgroups(groups) B set list of supplement l ssoci ted gid C2ni)D setpgrp() B c ll system function1 C2ni)D getppid()A intE p rentGs pid C2ni)D setsid() B c ll system function1 C2ni)D getpgid(pid)A intE process group id of process id pid C9IcurrentD C2ni)D getsid(pid) B c ll system function1 C2ni)D setpgid(pid(pgrp) B set process pid group to pgrp1 C2ni)D
&

A=I_=I< A 1E ignore sign l h ndler function <A=I A intE highest sign l number O1 :odule also defines si+nal nu$ ers =Posi* e*a$(les - runti$e definition is (latfor$ de(endant> C A=IQES ter$inal or control (rocessus disconnection A=I=<@ key oard interru(t A=IVE=@ ;uit re;uest fro$ key oard A=I=MM ille+al instruction A=ILPD@ a ort sto( si+nal A=IHSG floatin+ (oint error A=IU=MM the ,1LL si+nal A=IAGIO in#alid $e$ory reference A=IS=SG (i(e -rite -ithout reader A=ILMD? alar$ ti$er ela(sed A=I@GD? ter$ination si+nal A=IEAD user si+nal & A=IEAD! user si+nal 2 A=INQMC ter$inated2sto((ed child A=IN><@ continue (rocess =if sto((ed> A=IA@>S sto( (rocess A=I@A@S sto( re;uest fro$ key oard A=I@@=< read on tty -hile in ack+round A=I@@>E -rite on tty -hile in ack+round L D see your (latfor$ docu$entation =man # $i%na& on Linu*>. )unctions to send si+nals are in os $odule C kill(pid(sig) B kill process pid :ith sign l sig C2ni)D killpg(pgid(sig) B kill process group pgid :ith sign l sig C2ni)D Simple $&ternal 'rocess !ontrol 7se standard $odule subprocess. 1t -ra(s e*ternal (rocess creation and control in Qopen o 3ects. Child (rocess e*ce(tions raised efore e*ecution are re-raised in (arent (rocess4 e*ce(tions -ill ha#e child_traceback attri ute =strin+>. 5ote C subprocess tools -ill ne#er call 2 in2sh i$(licitly. S=SG A )1E const nt + lue used for Sopen stdin stdout stderr p r ms call(+args(++kwargs)A intE run comm nd :ith rguments" : it for completion" return retcode ; con+enient :r pper round Qopen object 7se Qopen o 3ects as (rocess control tools C p * Sopen(args(bufsi,eH (executableHNone(stdinHNone(stdoutHNone( stderrHNone(preexec_fnHNone(close_fdsHFalse(s ellHFalse(cwdHNone( envHNone(universal_newlinesHFalse(startupinfoHNone(creationflagsH ) args is a strin+2list of strin+s ['(omman)','ar%1','ar%*',] bufsi,e like for file2open functions executable can e used to (ro#ide co$$and in (lace of ar%$[+] stdin4 stdout and stderr can e S=SG to ca(ture file and co$$unicate -ith su (rocess preexec_fn is called 3ust efore child (rocess e*ecution close_fds ool force su (rocess inherited files to e closed4 e*ce(t 0 & and 2 s ell ool force e*ecution of co$$and throu+ht the shell cwd strin+ s(ecify -orkin+ directory to set for su (rocess start env dictionnary s(ecify en#iron$ent #aria les for su (rocess universal_newlines translate all ne-lines to >n =like G $ode for files> startupinfo and creationflags are o(tional infor$ations for (rocess creation under Mindo-s p.poll()A int&NoneE check child process termin tion" return returncode ttribute p.wait()A intE : it for child process to termin te" return returncode ttribute p.communicate(input-&one)A (stdout(stderr)E send d t Cinput stringDto stdin" re d d t from stdout&stderr until end;of;file" : it process to termin te" return re d + lues ; d t re d is buffered in memory p.stdin A file&NoneE st nd rd input from chil process if c ptured p.stdout A file&NoneE st nd rd output from chil process if c ptured 14b

p.stderr A file&NoneE error output from chil process if c ptured p.pid A intE process I, of child process p.returncode A int&NoneE child process return code CNone if not termin tedD ; on 2ni) ;! for subprocess termin ted by sign l ! 7se subprocess $odule -hen (ossi le =cleaner4 si$(ler interface4 see docs for e*a$(les>. /ee also e*ternal $odule pexpect. Ad(anced $&ternal 'rocess !ontrol /ee follo-in+ functions fro$ os $odule. execl(pat ([arg[(L!!) execle(pat ([arg[(L!!(env) execlp(file([arg[(L!!) execlpe(file([arg[(L!!(env) execv(pat (args) execve(pat (args(env) execvp(file(args) execvpe(file(args(env) Mith exec[ ne- (ro+ra$ re(lace current (rocess =fct donOt return>. OpO #ersions use P?8F to locate e*ecuta le file. OeO #ersions use a dict env to setu( ne- (ro+ra$ en#iron$ent. OlO #ersions use a (ositioned arg4 OvO #ersions use list of #aria le args. spawnl(mode(pat ([arg[(L!!)D int spawnle(mode(pat ([arg[(L!!(env) D int spawnlp(mode(file([arg[(L!!)D int spawnlpe(mode(file([arg[(L!!(env) D int spawnv(mode(pat (args) D int spawnve(mode(pat (args(env) D int spawnvp(mode(file(args) D int spawnvpe(mode(file(args(env) D int Mith spawn[ ne- (rocess is created. Ol(e#O #ersions like for exec[. 1f mode is S_<>KL=@ or S_<>KL=@B4 return child (id =7ni*> or (rocess handle =Mindo-s>. 1f mode is S_KL=@4 -ait child ter$ination and return its e*it code =W0> or its killin+ si+nal =Z0>. 'n Mindo-s $ode can e4 S_CG@LNQ =sa$e as S_<>KL=@ ut ne- (rocess detached fro$ callin+ (rocess console> or S_>OGDMLR =current (rocess is re(laced>. fork()A pidE fork child process" return 9 in child" child pid in p rent C2ni)D forkpty()A (intS2T)E Cpid"fdDE fork using ne: pseudo;termin l for child ; pid is in child" child pid in p rent ; fd pseudo;termin l m ster end C2ni)D startfile(pat ) B open file p th s if double;clicked in e)plorer C<indo:sD system(cmd)A + lueE e)ecute string cmd in subshell ; gener lly return Cpid&st tusD C2ni)D or st tus C<indo:sD wait()A (intS2T)E Cpid"st tusD : it completion of child process C2ni)D ; st tusI xTTTT :here TTIe)it code" TTIsign l num waitpid(pid(options)A (intS2T)E Cpid"st tusD C2ni)DE pidJ9 : it for specific process" pidI9 : it for ny child in process group" pidI;1 : it for ny child of current process" pidH;1 : it for ny process in process group ;pid option in <!O>A!@" <$O!TI!2'," <2!T#A$', st tusI xTTTT :here TTIe)it code" TTIsign l num waitpid(pid(options)A (intS2T)E Cpid"st tusD C<indo:sDE pid is ny process h ndle CJ9D ; option ignored ; st tusI xTT :here TTIe)it code Status infor ations e$traction KN>DGCE?S(status)A boolE test process gener ted core;dump C2ni)D K=HN><@=<EGC(status)A boolE test process continued from job control stop C2ni)D K=HA@>SSGC(status)A boolE test process stopped C2ni)D K=HA=I<LMGC(status)A boolE test e)ited on sign l C2ni)D K=HGF=@GC(status)A boolE test process e)ited +i e)itC2D system c ll C2ni)D KGF=@A@L@EA(status)A intE if e)ited +i e)itC2D" return e)it p r meter C2ni)D KA@>SA=I(status)A intE sign l h +ing stopped process C2ni)D K@GD?A=I(status)A intE sign l h +ing e)ited process C2ni)D 14c

/ee $anual for se$antics. *i in's9 "riority

times()A (ut(st(cut(cst(ert)E (flo tYdel yS0T)E user time" system time" childrenGs user time" childrenGs system time" el psed re l time nice(increment)A intE renice process ; return ne: niceness C2ni)D Me ory plock(op) B lock progr m segments into memory ; see Hsys&lock.hJ for op + lues C2ni)D Host Infor ations strerror(code)A strE error mess ge for the error code uname()A tupleE current oper ting system identific tion" Csysn me" noden me" rele se" +ersion" m chineD Crecent 2ni)D sys.byteorder A strE host n ti+e byte order big or little sys.winver A strE +ersion number for registry keys C<indo:sD sys.platform A strE pl tform identifier Ce). linux(D )ollo-in+ data are in os and in os.path. defpath A strE se rch p th for os.exec+p+() nd os.spawn+p+() if en+ironment *AT> not defined linesep A strE end of line ch rCsD for the pl ftorm devnull A strE file p th of null de+ice "ython Infor ations sys.builtin_module_names A (str)E n mes of modules compiled into interpreter sys.copyright A strE copyright of interpreter sys.hexversion A intE *ython +ersion :ith one digit by byte sys.version A strE interpreter +ersion O build O compiler sys.dllhandle A intE h ndle of *ython ,(( C<indo:sD sys.executable A strE n me of interpreter e)ecut ble bin ry sys.prefix A strE directory prefi) for pl tform independ nt *ython files sys.api_version A intE +ersion of *ython $ A*I sys.version_info A "intS-T,str(int)E Cm jor" minor" micro" rele sele+el" seri lD ; rele se in alpha" beta" candidate" final Signal 3andling /tandard $odule signal. /ee doc for +eneral rules a out si+nals usa+e in Python. /i+nal handlers are calla le f(signalnum(stackframe). alarm(time)A flo tYdel yE pre+ious l rm rem ining time ; re1uest ne: SI@A(#% in time seconds ; c ncel pre+ious one ; timeW9 C2ni)D alarm( )A flo tYdel yE pre+ious l rm rem ining time ; c ncel pre+ious l rm C2ni)D getsignal(signalnum)A fctE current sign l h ndler or SI@YI@! or SI@Y,F( or !one Ch ndler not inst lled from *ythonD pause() B sleep process until sign l is recei+ed C2ni)D signal(signalnum( andler)A fctE pre+ious h ndler for sign l C s getsignalD ; inst ll ne: h ndler Cm ybe SI@YI@! or SI@Y,F( tooD ; only c ll ble in m in thre d )ollo-in+ si+nal constants are defined C A=I_CHM A E def ult sign l h ndler function 14a

"ipes On "rocess 8hree functions a#aila le in popen! $odule =and in os $odule -here stdin2stdout return #alues are in#erted>. popen!(cmd[(bufsi,e[(mode!!)A (fileS2T)E Cstdout"stdinDE e)ecute cmd s sub;process popenZ(cmd[(bufsi,e[(mode!!)A (fileS-T)E Cstdout"stdin"stderrDE e)ecute cmd s sub;process popen\(cmd[(bufsi,e[(mode!!)A (fileS2T)E stdoutYstderr"stdinDE e)ecute cmd s sub;process Mhere bufsi,e is uffer siAe for 12' (i(es4 and mode is ?b? = inary strea$s> or ?t? =te*t strea$s4 default>. Para$ cmd is a strin+ (assed to os.system - on 7ni* it can e a se;uence of strin+s (assed directly to the (ro+ra$ -ithout shell inter#ention. 'n 7ni*4 popen! $odule also defines Qopen4 class =used in popen! and popenZ functions> and Qopen' class =used in popen\ function> C SopenZ(cmd[(capturestderr[(bufsi,e!!)A Qopen4E cmdE str shell comm nd" captudestderrE bool Cdef ult FalseD Sopen\(cmd[(bufsi,e!)A Qopen' Po(en9 and Po(en4 o 3ects ha#e follo-in+ attri utes C p.poll()A intE child return code or )1 if child not termin ted p.wait()A intE child return code p.fromchild A fileE output from child Cstdout nd stderr for Qopen'D p.tochild A fileE input to child p.childerr A fileE error output from child if re1uested else !one C!one for Qopen'D p.pid A intE child process pid /ee also $odule commands =7ni*>.

& 2

)eature na$es in xml.sax.handler as feature_xxx. Pro(erty na$es in xml.sax.handler as property_xxx. InputSource Interface

2*2Han!ler Interface 6efined in xml.sax.handler. 1ts $ethods are handlers called -hen (arser need 686 relati#e -ork. d * 2yATA/andler() A ATA/andler subcl ss object d .notationCecl(name4public@d(s+stem@d) B not tion decl r tion d .unparsedGntityCecl(name(public@d(s+stem@d(ndata) B unp rsed entity decl r tion #ntity-esol&er Interface 6efined in xml.sax.handler. 1ts $ethods are handlers called -hen (arser need e*ternal entity resolution. er * 2y3ntityEesol#er() A 3ntityEesol#er interf ce object er.resolveGntity(public@d(s+stem@d) A str&+nput0ourceE def ult return systemId #$ceptions 6efined in xml.sax $odule. 01[3xception(msg[(exception!) 01[Qarse3xception(msg(exception(locator) ^ in#alid B:L 01[NotEecognized3xception(msg[(exception!) 01[Not0upported3xception(msg[(exception!) #rrorHan!ler Interface 6efined in xml.sax.handler. 1ts $ethods are handlers called -hen (arser detect an error. 8heir exception (ara$eters +et 01[Qarse3xception o 3ects. e * 2y3rro/andler() A 3rror/andler interf ce object e .error(exception) B reco+erer ble error ; p rsing :ill continue if method return e .fatalGrror(exception) B unreco+er ble error ; p rsing must stop e .warning(exception) B minor : rning ; p rsing :ill continue if method return SA: /tilities 6efined in xml.sax.saxutils. escape(data[(entities!) A strE ^ < % esc ped ; esc pe other entities repl cing m pping strings CkeysD by corresponding identifiers unescape(data[(entities!) A strE ^amp\ ^lt\ ^gt\ unesc ped ; unesc pe other entities repl cing m pping identifiers CkeysD by corresponding strings ;uoteattr(data[(entities!) A strE s escape O 1uote string to be used s ttribute + lue prepare_input_source(source[(base!) A +nput0ourceE source is string" file;like" or +nput0ource ; base is n 2#( string ; return +nput0ource for p rser Class [2PWenerator is a .ontent/andler -ritin+ /?B e#ents into an B:L docu$ent =ie. re(roduce ori+inal docu$ent>. F?MIenerator([out[(encoding!!) A content h ndlerE out file;like" de ult to sys.stdout ; encoding def ult to ?iso)DD6B)1? Class [2PFilterSase is a default (ass-throu+ht e#ents4 can e su classed to $odify e#ents on-fly efore their (rocessin+ y a((lication handlers. F?MHilterPase(base) A e+ents filter ,eatures 3 "roperties 6efined in xml.sax.handler. 6ont +i#e their #alue4 ut their $eanin+. feature_namespaces1 A TrueE perform n mesp ce processing. FalseE no n mesp ce processing Cso no n mesp ce prefi)esD. feature_namespace_prefixes1 A TrueE report origin l prefi)ed n mes nd ttributes used for n mesp ce decl r tions. feature_string_interning1 A TrueE intern ll n mes Celements" prefi)es" ttributes" n mesp ce 2#Is" loc l n mesD. feature_validation1 A TrueE report ll + lid tion errors. feature_external_ges1 A TrueE include ll e)tern l gener l Cte)tD entities. feature_external_pes1 A TrueE include ll e)tern l p r meter entities" including the e)tern l ,T, subset. 15c

Pro#ide source of data for (arser. isrc.setSublic=d(id) B set public identifier isrc.getSublic=d() A unicodeE public identifier isrc.setAystem=d(id) B set system identifier isrc.getAystem=d() A unicodeE system identifier isrc.setGncoding(encoding) B set encoding ; must be string ccept ble for n ?%( encoding decl r tion ; ignored if InputSource cont ins ch r cter stre m isrc.getGncoding() A str&None Cif unkno:nD isrc.setPyteAtream(b+tefile) B set input byte stre m ; ignored if InputSource cont ins ch r cter stre m isrc.getPyteAtream() A byte stre m isrc.setNharacterAtream(c arfile) B set ch r cter C2nicodeD stre m isrc.getNharacterAtream() A ch r cter stre m Locator Interface 1nstances of Locator (ro#ide these $ethodsC loc.getNolumn<umber() A intE column number :here current e+ent ends loc.getMine<umber() A intE line number :here current e+ent ends loc.getSublic=d() A strE public identifier of current e+ent loc.getAystem=d() A strE system identifier of current e+ent Attributes Interface ?lso i$(le$ent (arts $a((in+ (rotocol =copy()4 get()4 has_key()4 items()4 keys()4 and values()>. ai.getMength() A intE number of ttributes ai.get<ames() A [unicode]E n mes of ttributes ai.get@ype(name)A type of ttribute n me ; norm lly ?.A1T1? ai.getOalue(name)A unicodeE + lue of ttribute n me Attributes.S Interface ?lso i$(le$ent 1ttributes interface. ansi.getOaluePyV<ame(name)A unicodeE + lue of ttribute 1u lified n me ansi.get<amePyV<ame(name)A (unicodeS2T)E Cn mesp ce" loc ln meD for 1u lified n me ansi.getV<amePy<ame(namepair)A unicodeE 1u lified n me for Cn mesp ce" loc ln meD ansi.getV<ames()A [unicode]E 1u lified n mes of ll ttributes ContentHan!ler Interface 6efined in xml.sax.handler. 1ts $ethods are handlers called -hen (arser find B:L structures. c * 2y.ontent/andler() A .ontent/andler subcl ss object c .setCocumentMocator(locator) B set loc tor for origin of document e+ents c .startCocument() B beginning of document c .endCocument() B end of document c .startSrefix?apping(prefix(uri) B begin of prefi);2#I n mesp ce m pping ; see doc c .endSrefix?apping(prefix) B end of prefi);2#I n mesp ce m pping c .startGlement(name(attrs) B st rt of n element ; non;n mesp ce mode ; attrs h s n 1ttributes interf ce Cm y be reused ; copy d t D c .endGlement(name) B end of n element ; non;n mesp ce mode c .startGlement<A(name(8name(attrs) B st rt of n element ; n mesp ce mode ; name is Curi"loc ln meD ; 8name is r : ?%( n me ; ttrs h s n 1ttributesN0 interf ce Cm y be reused ; copy d t D ; 8name m y be None Cupon fe tureYn mesp ceYprefi)esD c .endGlement<A(name(8name) B end of n element ; n mesp ce mode c .characters(content) B ch r cter d t ; content is str or unicode c .ignorableKhitespace(w itespace) B :hitesp ces c .processing=nstruction(target(data) B processing instruction c .skippedGntity(name) B entity not processed

XML PROCESSING
/e#eral $odules to (rocess B:L are a#aila le. /o$e -ith standard /?B and 6': interfaces4 others -ith $ore Pythonic interfaces. /ee also third (arty SyF?M e*tension (acka+e. SA4 0 $(ent0dri(en .ase functions in xml.sax $odule. make_parser([parser_list!) A [2PEeaderE built from first p rser + il ble parse(filename_or_stream(content_ andler[(error_ andler!) B p rse document using first p rser + il ble parseAtring(string(content_ andler[(error_ andler!) B p rse string using first p rser + il ble :ML-ea!er Interface 6efined in xml.sax.xmlreader. p * xml.sax.make_parser() A [2PEeader object p.parse(source) B completly p rse source ; source is filen me or 2#( or file; like or InputSource; input byte stre ms Cnot ch r cter stre msD p.getNontentQandler() A .ontent/andlerE current one p.setNontentQandler( andler) B set current content h ndler p.getC@CQandler() A ATA/andlerE current one p.setC@CQandler( andler) B set current ,T, h ndler p.getGntityDesolver() A 3ntityEesol#erE current one p.setGntityDesolver( andler) B set current entity resol+er p.getGrrorQandler() A 3rror/andlerE current one p.setGrrorQandler( andler) B set current error h ndler p.setMocale(locale) B set loc le for errors nd : rnings p.getHeature(featurename) A current settings for fe ture1 p.setHeature(featurename(value) B set fe ture to + lue p.getSroperty(propert+name) A current settings for property2 p.setSroperty(propert+name(value) B set property to + lue 8here is also an +ncrementalQarser su class interface -ith C p.feed(data) B process chunk of d t p.close() B ssume end of document" check :ell;formedness" cle nup p.reset() B fter close" prep re ne: p rsing 15a

15b

all_features A list of ll fe tures property_lexical_handler A option l e)tension h ndler for le)ic l e+ents Clike commentsD. property_declaration_handler A option l e)tension h ndler for ,T,; rel ted e+ents other th n not tions nd unp rsed entities. property_dom_node1 A +isited ,O% node Cif ,O% iter torD :hen p rsing" else root ,O% node. property_xml_string A liter l string source of current e+ent Cre d only propertyD. all_properties A list of ll properties n mes
&

.o!eList ? se;uence of nodes4 usa le as a Python se;uence =$ay e $odifia le u(on i$(le$entation>. o.length A intE number of nodes in the se1uence o.item(i) A Node&NoneE ith item in the list 2ocu ent*ype /u class of Node. o.node@ype A C>NE?G<@_@RSG_<>CG o.public=d A unicode&NoneE public identifier for e)tern l subset of ,T, o.system=d A unicode&NoneE system identifier 2#I for e)tern l subset of ,T, o.internalAubset A unicode&NoneE complete intern l subset from the document ; :ithout br ckets o.name A unicode&NoneE n me of root element C s gi+en in ,O$T_*'D o.entities A NamedNode2ap&NoneE definition of e)tern l entities o.notations A NamedNode2ap&NoneE definition of not tions 2ocu ent /u class of Node. o.node@ype A C>NE?G<@_<>CG o.documentGlement A 3lementE root element of the document o.createGlement(tag&ame)A 3lementE ne:1 element node o.createGlement<A(namespace?A@(tag&ame)A 3lementE ne:1 element node :ith n mesp ce ; tag&ame m y h +e prefi) o.create@ext<ode(data) A 3lementE ne:1 te)t node cont ining d t o.createNomment(data) A 3lementE ne:1 comment node cont ining d t o.createSrocessing=nstruction(target(data) A 3lementE ne:1 processing instruction node cont ining t rget nd d t o.createLttribute(name) A 3lementE ne:1 ttribute node o.createLttribute<A(namespace?A@(8ualified&ame) A 3lementE ne:1 ttribute node :ith n mesp ce ; tag&ame m y h +e prefi) o.getGlementsPy@ag<ame(tag&ame) A NodePistE se rch for ll descend nts Cdeep se rchD h +ing type tag&ame o.getGlementsPy@ag<ame<A(namespace?A@(local&ame) A NodePistE se rch for ll descend nts Cdeep se rchD h +ing namespace?A@ nd local&ame Cp rt fter prefi)D
&

Attr /u class of Node. o.node@ype A L@@D=PE@G_<>CG o.name A unicodeE CroD ttribute full n me ; m y h +e colons o.local<ame A unicodeE CroD ttribute n me ; p rt fter colons o.prefix A unicodeE CroD ttribute prefi) ; p rt before colons ; m y be empty .a e!.o!eMap ? $a((in+ of nodes - e*(eri$entally usa le as a Python $a((in+. o.length A intE length of ttributes list o.item(index) A 1ttrE ttribute t inde) ; rbitr ry but consistent order Co ent /u class of Node. Cannot ha#e su node. o.node@ype A N>??G<@_<>CG o.data A unicodeE content of the comment" :ithout <R)) nd ))% *e$t /u classes of Node. Cannot ha#e su node. 8e*t (art in an ele$ent. o.node@ype A @GF@_<>CG o.data A unicodeE te)t content C2A*ASection /u classes of Node. Cannot ha#e su node. C6?8? section in a docu$ent4 $ay ha#e $ulti(le C6?8?/ection nodes for one C6?8?. o.node@ype A NCL@L_AGN@=><_<>CG o.data A unicodeE $,ATA content "rocessin'Instruction /u classes of Node. Cannot ha#e su node. Re(resents a (rocessin+ instruction in the B:L docu$entJ this inherits fro$ the 5ode interface and cannot ha#e child nodes. o.node@ype A SD>NGAA=<I_=<A@DEN@=><_<>CG o.target A unicodeE CroD processing instruction content up to first :hitesp ce o.data A unicodeE CroD processing instruction content fter first :hitesp ce #$ceptions Python $a( 6': error codes to e*ce(tions.
DOM 7o.), 7on,t&nt, E97)pt-on

can only e read durin+ (arsin+ =and $odified efore>.

)O" 0 In0memory Tree 6efined in xml.dom. 8-o function to re+ister2access 6': (rocessors4 and so$e constants. registerC>?=mplementation(name(factor+) B register ,O% implement tion f ctory getC>?=mplementation([name[(features!!> A ,O% implement tion ; n me m y be None ; m y found n me in en+. + r *_T>O!Y,O% ; fe tures is KCfe turen me"+ersionD"FL G?S@R_<L?GASLNG A no n mesp ce ssoci ted :ith node F?M_<L?GASLNG A )ml prefi) n mesp ce F?M<A_<L?GASLNG A n mesp ce 2#I for n mesp ce decl r tions ; ,O% le+el 2 specific tion definition FQ@?M_<L?GASLNG A 2#I of ?>T%( n mesp ce C?>T%( 1.9D 2OMI ple entation impl.hasHeature(feature(version) A boolE test for supported fe ture in n implement tion .o!e 6efined in xml.dom4 class Node is (arent of B:L co$(onents nodes classes. o.node@ype A intE CroD in GMG?G<@_<>CG" L@@D=PE@G_<>CG" @GF@_<>CG" NCL@L_AGN@=><_<>CG" G<@=@R_<>CG" SD>NGAA=<I_=<A@DEN@=><_<>CG" N>??G<@_<>CG" C>NE?G<@_<>CG" C>NE?G<@_@RSG_<>CG" <>@L@=><_<>CG o.parent<ode A Node&NoneE CroD ; !one for 1ttr nodes o.attributes A NamedNode2ap&NoneE ttribute objects for elements" else None o.previousAibling A Node&NoneE CroD pre+ious node in p rentGs children o.nextAibling A Node&NoneE CroD ne)t node in p rentGs children o.child<odes A [Node]E CroD list of subnodes o.firstNhild A Node&NoneE CroD first subnode o.lastNhild A Node&NoneE CroD l st subnode o.local<ame A unicode&NoneE CroD element n me :ithout n mesp ce prefi) o.prefix A unicode&NoneE CroD element n mesp ce prefi) ; m y be empty string or None o.namespaceED= A unicode&NoneE CroD 2#I ssoci ted to element n mesp ce o.node<ame A unicode&NoneE CroD us ge specified in subcl sses o.nodeOalue A unicode&NoneE CroD us ge specified in subcl sses o.hasLttributes() A boolE test ny ttribute e)istence o.hasNhild<odes() A boolE test ny subnode e)istence o.isAame<ode(ot er) A boolE test other refers s me node o.appendNhild(new% ild) A ne: $hildE dd ne: child node t end of subnodes ; return ne: child o.insertPefore(new% ild(ref% ild) A ne: $hildE dd ne: child node before n e)isting subnode ; t end of subnodes if ref$hild is !one ; return ne: child o.removeNhild(old% ild) A old% ildE remo+e subnode" return it ; :hen no longer used" must c ll old% ild.unlink() o.replaceNhild(new% ild(old% ild) B repl ce e)isting subnode :ith ne: one o.normali"e() B join dj cent te)t nodes o.clone<ode(deep) A NodeE if deep" clone subnodes too ; return clone

5e- nodes are standalone - you $ust insert2associate the$ in2to docu$ent (arts. #le ent /u class of Node. o.node@ype A GMG?G<@_<>CG o.tag<ame A unicodeE element type n me ; :ith n mesp ce m y cont in colons o.getGlementsPy@ag<ame(tag&ame) A NodePistE se rch for ll descend nts Cdeep se rchD h +ing type tag&ame o.getGlementsPy@ag<ame<A(namespace?A@(local&ame) A NodePistE se rch for ll descend nts Cdeep se rchD h +ing namespace?A@ nd local&ame Cp rt fter prefi)D o.getLttribute(attname)A unicodeE ttribute + lue o.getLttribute<ode(attrname)A 1ttrE ttribute node o.getLttribute<A=namespace?A@(local&ame)A unicodeE ttribute + lue o.getLttribute<ode<A(namespace?A@(local&ame)A 1ttrE ttribute node o.removeLttribute(attname) B remo+e ttribute by n me ; ignore missing ttribute o.removeLttribute<ode(old9ttr)A 1ttrE remo+e nd return old9ttr o.removeLttribute<A(namespace?A@(local&ame) B remo+e ttribute by n mesp ce 2#I nd n me ; ignore missing ttribute o.setLttribute(attname(value) B set ttribute string + lue o.setLttribute<ode(new9ttr)A 1ttrE set ttribute from ne: 1ttr node ; return old one o.setLttribute<ode<A(new9ttr)A 1ttrE set ttribute from ne: 1ttr node :ith n mesp ce 2#I nd loc l n me ; return old one o.setLttribute<A(namespace?A@(8name(value)A 1ttrE set ttribute string value from namespace?A@ nd 8name C:hole ttribute n meD ; return old one 16b

C>?A@D=<I_A=WG_GDD Q=GDLDNQR_DGVEGA@_GDD =<CGF_A=WG_GDD =<EAG_L@@D=PE@G_GDD =<OLM=C_LNNGAA_GDD =<OLM=C_NQLDLN@GD_GDD =<OLM=C_?>C=H=NL@=><_GDD =<OLM=C_A@L@G_GDD <L?GASLNG_GDD <>@_H>E<C_GDD <>@_AESS>D@GC_GDD <>_CL@L_LMM>KGC_GDD <>_?>C=H=NL@=><_LMM>KGC_GDD AR<@LF_GDD KD><I_C>NE?G<@_GDD

Aomstring0ize3rr /ierarchyEeYuest3rr +ndex0ize3rr +nuse1ttribute3rr +n#alid1ccess3rr +n#alid.haracter3rr +n#alid2odification3rr +n#alid0tate3rr Namespace3rr NotFound3rr Not0upported3rr NoAata1llowed3rr No2odification1llowed3rr 0yntax3rr 9rongAocument3rr

exception:code A intE ,O% code corresponding to e)ception exception:msg A stringE mess ge for e)ception AU23xception Aomstring0ize3rr ^ i$(le$entation li$it reach /ierarchyEeYuest3rr ^ insert at -ron+ (lace +ndex0ize3rr ^ inde* ran+e error +nuse1ttribute3rr ^ ?ttr node already used in tree +n#alid1ccess3rr ^ (ara$2o(eration unsu((orted y o 3ect +n#alid.haracter3rr ^ character in#alid in the conte*t +n#alid2odification3rr ^ canOt $odify node ty(e +n#alid0tate3rr ^ try to use an undefined2unusa le o 3ect 16c

16a

Namespace3rr ^ chan+e for idden in na$es(ace conte*t NotFound3rr ^ node donOt e*ist in referenced conte*t Not0upported3rr ^ o(eration2ty(e unsu((orted y i$(le$entation NoAata1llowed3rr ^ no data for this node No2odification1llowed3rr ^ canOt $odify o 3ect 0yntax3rr ^ in#alide2ille+al strin+ 9rongAocument3rr ^ i$(l. canOt $i+rate nodes et-een docs

attri utes =o(tional>. Connection connect(dsn[(user[(password[( ost[(database!!!!)A $onnection object Cinterf ce defined s guidelineD ; dsnId t source n me string cx.errorhandler A fctE Coption lD h ndler for connection errors ; errorh ndlerCconnection" cursor&!one" errorcl ss" error+ lueD ; def ult h ndler fill c).mess ges nd m y r ise e)ceptions cx.messages A [(e)ception cl ss(e)ception + lue)]E Coption lD mess ges recei+ed from d t b se for oper tions :ith connection cx.close() B termin te connection Cm y rollb ck if not commitedD cx.commit() B commit pending tr ns ctions cx.rollback() B rollb ck pending tr ns ctions Coptionn lD cx.cursor()A ne: .ursor object Cursor cu.arraysi"e A intE C#<D number of ro:s to fetch :ith fetchmany ; def ult to 1 cu.connection A .onnectionE Coption lD connection used by cursor cu.description A [(n me( typeYcode( displ yYsi4e( intern lYsi4e( precision( sc le( nullYok)]&NoneE describe result columns cu.errorhandler A fctE Coption lD h ndler for connection errors ; errorh ndlerCconnection" cursor" errorcl ss" error+ lueD ; def ult h ndler fill c).mess ges nd m y r ise e)ceptions ; inherited from connection cu.lastrowid A int&NoneE Coption lD ro: id of l st modified column cu.messages A [(exception class(exception value)]E Coption lD mess ges recei+ed from d t b se for oper tions :ith cursor cu.rowcount A intE number of ro:s produced& ffected by l st re1uest ; )1 or None if re1uest c nt touch ro:s cu.rownumber A int&NoneE Coption lD 9;b sed inde) of the cursor in the result set if + il ble cu.callproc(procname[(parameters!)A (p r meters) ; Coption lD c ll ,B stored procedure ; in result out nd inout p r meters m y h +e been repl ced by procedure cu.close()` close the cursor cu.execute(oper[(params!) B prep re nd e)ecute ,B re1uest ; params1 is se1uence or m pping Csee module p r mstyle + ri bleD cu.executemany(oper(params_se8) B like e)ecute" :ith se1uence of params Cfor multiple + luesD cu.fetchone()A (columnY+ lue(F) & NoneE ne)t ro: of 1uery result" !one :hen no more d t + il ble cu.fetchmany([si,e!)A KCcolumnY+ lueDLE ne)t set of ro:s of 1uery result" empty list :hen no more d t + il ble ; si,e def ult to cu.arraysi"e cu.fetchall()A [(columnY+ lue)]E ll rem ining ro:s of 1uery result" empty list :hen no more d t + il ble cu.next()A (columnY+ lue) E Coption lD ne)t ro: of 1uery result" r ises 0top+teration :hen no more d t + il ble cu.nextset() A True&NoneE Coption lD disc rds results up to ne)t + il ble set cu.scroll(value[(mode!) B Coption lD ; scroll cursor in current result set ; mode is ?relati#e? Cdef ultD or ?absolute?. cu.setinputsi"es(si,es) B predefine memory re s for executeFFF oper tions p r meters ; si,esIKp r mYsi4e"FL ; p r mYsi4eIType Object or int Cm ) length of string p r mD ; p r mYsi4eINone for no predefinition cu.setoutputsi"e(si,e[(column!) B set column buffer si4e for fetches of l rge columns Ce.g. (O!@s" B(OBs" etc.D by executeFFF ; column is inde) in result ; ll columns if column not specified cu.__iter__() A .ursorE Coption lD object itself
&

DATABASES
/ee Python.or+ -iki for a list of data ase interface $odules. /o$e interfaces are for e*ternal 6. en+ines =:y/QL4 Post+re/QL4 .erkeley6.4 /QLite4 :etakitL>4 other for (ure Python 6. en+ines =+adfly4 I'6.4 ,irky.ase4 .uAhu+L>. 5eneric access to )B"0style )Bs /tandard $odule anydbm is a front-end to so$e a#aila le 6. $odules C dbhash =DbsddbD.erkeley 6.>4 gdbm =DG57 d $>4 dbm =Duni* d $> and the slo- (orta le fall ack dumbdbm. 6ata stored in 6.:-style files are accessed #ia a dictionary-like interface -here keys and #alues $ust e str. open(filename[(flag[(mode!!) A diction ry;like objectE flag in ?r? Cre d; def ultD" ?w? C:riteD" ?c? Ccre te if doesnGt e)istD" ?n? Ccre te ne: emptyD ; mode is uni) mode fl gs for cre tion error A tuple of e)ception cl sses from ,B modules C nydbm.error"FD 7ses $odule whichdb to identify ri+ht 6. $odule for e*istin+ file. )or ne- files4 use first a#aila le 6. $odule in the order of the list. 8his is used y shelve $odule =see Persistence4 (&2>. 6. $odules can ha#e s(ecific functions related to their ackend4 see docs. Standard )B A'I for S.% databases Generally $odules for /QL data ases use the /tandard Python 6ata ase ?P1 #2 =defined in P"P24@>. A"I Infor ations apilevel A strE currently ?1: ? or ?(: ? ; ?1: ? if undefined threadsafety A intE le+el of thre d s fety
:

@imestamp(+ear(mont (da+( our(minute(second)A object to hold time st mp + lue CateHrom@icks(ticks)A object to hold d te + lue from gi+en ticks + lue @imeHrom@icks(ticks)A object to hold time + lue from gi+en ticks + lue @imestampHrom@icks(ticks)A object to hold time st mp + lue from gi+en ticks + lue Pinary(string)A object to hold long bin ry string + lue /QL 57LL #alues re(resented y Python None. 2( types *ypeco!es A@D=<I A string;b sed column C$>A#D P=<LDR A long bin ry column C(O!@" #A<" B(OBsD <E?PGD A numeric column CL@G@=?G A d te&time column D>K=C A ro: I, column C$>A#D

BULK
*ools .atteries includedC pdb =Python de u++er>4 code ench -ith timeit =(@>. ? $ust ha#eC pychecker. 8ake a lookC pylint4 psyco4 pyrex4 pycount4 trace!html4 depgraph4 coverage4 pycover4 Syflakes4 pyreverse4 QLS. Lin+s 6ocsC htt(C22---.(ython.or+2doc2 )?Q PythonC htt(C22---.(ython.or+2doc2fa;2 P"PsC htt(C22---.(ython.or+2de#2(e(s2 =Python "nhance$ent Pro(osal> F'M8'sC htt(C22---.a$k.ca2(ython2ho-to2 Cook ookC htt(C22as(n.acti#estate.co$2?/P52Python2Cook ook2 6i#e 1ntoC htt(C22---.di#einto(ython.or+2

1 ( 4
+&(%)

,h&5) $o.%() no yes yes yes

,h&5) 7onn)7t-on, no no yes yes

,h&5) 7%5,o5, no no no yes )9&$p() na$eH_ na$eHC& na$eHCna$e na$eH]s na$eH]=na$e>s

paramstyle A strE p r meter m rker for re1uests ?Ymark? ?numeric? ?named? ?format? ?pyformat & Para$eters 2 Para$eters
p&5&$, Question $ark style& 5u$eric4 (ositional style& or 2 5a$ed style2 ?5/1 C (rintf for$at codes& Python e*tended for$at codes2 LMF"R" LMF"R" LMF"R" LMF"R" LMF"R"

2005-2007 - Laurent Pointal Zlaurent.(ointalala(oste.netW %0.Y7 2007-4-2@ License C Creati#e Co$$ons [ y nc sa!. PQRC at htt(C22laurent.(ointal.or+2(ython2(;rc Lon+ Python Quick Reference at htt(C22r+ruet.free.fr2 'ri+inal Python reference at htt(C22---.(ython.or+2doc

as (ositional #alues in a se;uence. as na$ed #alues in a $a(.

#$ceptions =0tandard3rror> 9arning ^ i$(ortant -arnin+ 3rror ^ a catch all +nterface3rror ^ (ro le$ -ith interface =not data ase> Aatabase3rror Aata3rror ^ (ro le$ -ith data (rocessin+ Uperational3rror ^ (ro le$ durin+ data ase o(erations +ntegrity3rror +nternal3rror Qrogramming3rror ^ /QL (ro+ra$$in+ related error Not0upported3rror "*ce(tions classes $ay also e a#aila le as .onnection o 3ects 17a

:ethod __getitem__ is used to +et #alues in (ara$s4 usin+ (osition or na$e. Can use tuple or dictL or your o-n class o 3ects -ith its __getitem__. 1f next and __iter__ are defined4 cursors are itera le. 2( types Constructors Cate(+ear(mont (da+)A object to hold d te + lue @ime= our(minute(second)A object to hold time + lue 17b 17c

You might also like