You are on page 1of 18
Python 2.4 Quick Reference Card 1©2005.2006 - Laurent Ponta! 056 — 2006.5 31 — PORC at hip lassnicaintal enya ong Python Quick Reference at mirage reas Original Python reference at nov wusoytnonowidoe License: Creative Commons [oy ne s3. Canos Convent career tase a) eegcrmen, : Seer eee | cece iste 3 oe 1) Spence Mia 1) Seetircsemastiesiencs 8 sdee 1) Serie scant ea ie 1 deren fest Sears ea meneame) See Scenics 2] Sera 3 Skeacrime mene [Sweats 8 See atc eon 9| Mare 3 = 3 Me 3 Cs neon’ 3] RES So ; post a) seater er spon 3 ne Aerts 2 ire 3) seuiscee x Parameters / Resurn value. 2| Fle Objects. i 10 seer <3] asta # Decorators. ~ 3] Terminal Operations. 1 enc alan 3] rcelones B ep 3] aay nae # eae 3) eee z Setikomes| peat a ses conne ee) saree 3) See i eet 3) cae Hl eee 3) See z nee 3) Beet # vee ae 3 lence 4 ae 3 sessed 8 SS tee, 3] te x ott ga) test 2 ‘i |i Seietin eerie 4] Teese ties. 8 ee 2 ene {Seis 8 Sees 4] Snares 3 =e | Sener ea ef oe rai Shoals i ‘soars 3 Se ras i oe | "Swine 2 cae 3] Semtera creat Searem mad) Sacer mart seh Satis 3) tees z sone ena as gbaiyeta i ap 3) SuniediivetoeSatoa aac Styles: xeyword Funct Lonlmethod toe replaced expression variable forts module module filename Zanguage ayatax Notations (39 ren value £ (> rewen nothing procedure) (41 fora ise of x data, (9 fora sspie of x data, may have xin n Kimes » data, EnvitonMenT VARIABLES PYTHONCASEOK na case stncton In module mapping PYTHONDEAUG =a commandline option PYIHONHOME Mody standard Python libs prefix and exec pref locations. Use |:) PYTHONINSPecT +1 commandsine oston PyTHONOPTIMIZE ‘0 commandsline option PYTHONPATH Directories where Python search when importing modulesipackages, Separator (posh) ot: (windows). Under windows use reaistry HKLMso‘warel, PYTHONSTARTUP Feta load st begining of interactive sessions PYTHONUNBUFFERED | =-u commande option PYIHONVERBOSE \ commandline option get to non-empty vale, ‘Commano-ine Orrions Bython -smoQsywin 0B) lemme aJ',) Write exprto ays aedou? Sie expr global Joel) Execute expr namespaces. (edlssoe,—,lnamecesae Call any callable abject fx with given gal kwargs) ‘arguments (see Funclions Delntions & Usage p2) Assignment operator ® Multiple statements on same line using ; separator - avd if nat pecessary 2 rite to any spectied abject following fle interface (write meth. ite space between expressions, line tetum at end of ne except with 2 Fal 53am part rame can be container expression. expr is a sequence of ‘ltipe values, can unpack into muliple names, Can have multiple assignments of same value on same ne: a ~ b= ¢= expr (ther statements (loops, conditons..) introduced in respective pats. Blocks ‘A: between statements defines dependant statements, written on same line or written on following nets) with deeper indentation, Blocks of Statements are simply lines at same Indentation level ‘Statement continuation lines don't care indentation. ‘a avald problems, configure your edtor ta use 4 spaces in place af thos Assignment Shortcuts seb ane ate aye Dine nae eee fee AIsb aN aoe acer Evaluate «once, and assign to a the result of operator before = applied to current a and. Example: stb = arate Consote & Interactive Input/Output “npue (prompt) evaluation of rer Input ped dat) ay_smput (prompt) 222" use input as 2 raw sting Direct manipulation (redefintion} of stinstdoutistderr via sys module All are files oF fles-ke objects. The _axx__ forms keep access to riginal standard (0 streams, CULE raises Seynonecscneeups exception Seip (object) > princ online documentation sya diaplayhook (ne) ftalu) called to display value Sys displayhook "> backup ef gina diplayhook function See external package ipython for an enhanced interactive Python shel Objects, Names ano NaMespacts. Identifiers Use <[a-2Az_la-28-20-9.1° Special usagé for underscore “ex giobal nok imperted by inact + Ek Implementation dela for internal use (good practice) Zit ‘prvate’ class members, defined as lsesnera xen ‘oo normally reserved by Python case is significant this sane '= fuze Objects and Names, Reference Counting Data are typed objects (all data), names are dynamically bound to objects, ~ assignment statement bind result of right part evaluation in name(sicontaner(s). Examples When an object is no longer referenced (by names or by containers), its destroyed fits _dea__ method i then called, sys. getzefcount (object) > ints curren reference counter of eect Standard module wakeet define tools to allow objects to be garbage collected when necessary and dynamically recreated on-demand, ‘Mutable /Immutable Objects Mutable objects can be modified in place. Immutable objects cannot be modified (ust buld new object with new value) Immutable "soci, st, 1005, 2104 Mutable | -~,=0:, cc and other nigh level class objects ‘There is no constant definition. Just use uppercase names To identity ‘symbols which must not be modified Namespaces Places where Python found names. Bulking namespace » names from module _wusitine_, already avalable Glabat namespace + names defined at module level {ero indentation). Local namespace » names delines in methodsfunctions, ol mame > remove existing name from namespace remove objet binding) (Globala() +srct:ldantfrevale of global namespace ocala () 34.ctsidentiiervale of fc mamespace lett part Curent scope + names directly usable. Searched in locals, then locals from enclosing definitions, then gibals, then buitins louratscope name + use the dotted attnbute notations. (maybe scuysest} where x i6 a name visible within the curent scope Class namespace + names defined ina clas (class members) (Object namespace + names usable withobect. name notation (attributes, methods). Namespaces can be nested, inner namespaces hsding identical names from outer namespaces. ie (lobjert) 2st: names defied in object mamespac! fas (object) ict Wentifervalue of ebect as 2 namespace! if object rat specined use nearest namespace locals) Fmastnot be modified Constants, Enumerations Use uppercase and _for constants identifiers (good practice). May define namespaces to gfup constants. Cannot avold gabaliocal name. Fedefiniion (can eventually define namespaces as clases with Brtibutes access contol hot In Pyshon spi, and exeeuton cost See third party modules pyenun for strict enurnike namespace Fiow Controt Condition Loop There sno ‘switch’ or case, Wh 26 cond: Inst Con use elle. else [Can use a mapaing win functions bound to cases ait op with neose {Go to next eration with continse, Loops ele blocs only executed wen loop exit normally (without seesk), Functions methods exit Enitfunction/methd with ==ts2= value) Ent from generator body with y= value Muliple relumed values using tuple data Cannet yseia within tyifinaly block. Exceptions Can have a tuple of classes for except class. Not specifying a class Eaten al exceptone, Block elze executed when sry black exit normaly [Process ¢:2a11y block in all execution paths (notmal or exception} Last form reraise the currently catched exception in an exception erable Protocol Generic and simpie protoc! allowing to iterate on any callecton af data (Objects of class defining ster or getiten_ ate erable (directly usable nf f00ps. _ster_(o0i) iteatar on see eer (object) > iterator on iterable object {iter (allele sentinel) iterator returning callable values upto sentne! enumerate terabe) iterator returning tuples Gindexvale) rom erable Iterator Objects Interface ext (2016) nextitem! ‘ter (2015) ierator object eel Twihen Feach end of collection, raise stoprteration exception on subsequent cals i, terator usable only one ime on a collection} Generators Functions retaining thelr state between two calls. Retum values using “yleis. stop generation via simple "esse oF via == 1) build generator from function: genegeneratrft (ar) 2) use gen.next() Values untl stoptsoration Is raised Generator iterable expressions with | (x So> «in erable cond) ‘Operations withion iterable See Operations on Containers (o8), See iteration Tools (9). lnvreneneramion / Execuion compte (tring! flename, kine age dont inberit)) 9 ode object svat (expression, global, local) value evaluation’ of expression sing val (code object global loc) “value eraluatin of code object Soiec? #atements (= glabal, local] ® rtatemente string! executed sxacesie (fname, glabal locate) Ale inerpreted 2 wuitine statements in source code must use \n as newline, and ‘pust be terminated by a newline "na relative to string cartent, "exec! + sequence of statements, fal" single expression, tzingle’ 2 single interactive statement fags and dont. inherit are fr future statements (see dod), {in context of lobals and locals namespaces. 5 Exee isa langage statement others ae buitin functions Funcvions Derinmrions & Usace variable lst of named parameters in Return valuets) with === [alu For mutpe values, retum a supe. fo rovucn value specified or tend ‘of function detntion reached, retum Sv value args, *+kwarg) Lambda functions ts param): expression “Anonymous funclons defined inne. Result of expression evaluation is retuned (must be an expression, no loop, ne condo). | Expression uses values known at deiiion Ume {except for params), Calable Objects Objects having a _ eat _method can be used as functions Methods bound to objects can be used as functions: f= 0. meth fealtapie (x) #00. tert x eallable with x.) Calling Functions [names] tename (xpi, mame-expr., arg. **arge) ‘Anonymous parameters passed In parameters order declaration Pararss oving default atu can be omitted, Notation * -» pass variable Ist of anonymous parameters in cups Notation ## > pass variable ist of named parameters inact Functions Control sys getzecuratontsmtt (1 int:carent recursion lini for functions sys-getecuraionlamtt (lt) set recursion ii for functions Decorators Glue code (unctions) calle at functions and methods definitions time, return the final functionimethod (generally with wrapping code). dscoratorame (decorator arguments 1 for fee tetrgumente) det gaecztargn) Qdecd ys sot fetid fe Ftd WS seem dect deczargs(ee3(0e0 09) See page PuhonDecoatorLtvary in python.org Wik for some decorators Tires /Ciasses & Owjects ‘ll data are typed object relying to classes. type) 9 ype: pe object of dard module -ypaz define type objects for bulns types. ‘lass Definition sos elaaname |(gazentcars'.)) See metname(oat 1) > define methods ke functions Support mutipe inheritance. Can inher rom builtin class, Inert atleast rom o> sect base class => Python new style class Fst parameter of methods is target object, standard use sex name. ‘Access class members via class name, object members via [Tis doc consider you use new style clas (inherting from ob: etaciass Class definition create anew type. It can be done "by hand’ with {x= type arename, (parentcate,.)),(warame! exp!) ise metrame( sent) ‘Thir allow creation of metaciass classes (class building other cas). Object Creation = ClazeName ntarge..) ii cas of exception cuing initalizaton, objects destroyed when exting Ini code (reterence counter reach 20) lasses & Objects Relations ainatance fl, catsina) -rboo stst object of ype/lascassinfo Sanubetass (aats,aparent) 3001 tet same las or parent relations [Prefer sinstance( to ypet) for type checkin, Parent class methods are not automatically called foveriden in Subclass they must be explety ealea it necessary. Call parent methods via super function super (Thislas, col) methodname sol, 795.) or te old way, via parent class namespace ParenClass. methodname oe, 795.) Attributes Manipulation object. mame» value te (object, name, value) > abject atiibute set to value [Geta (object, mame defat) > vale of obec acribute Sot objets mame [Salat (oblect, name) > object tribute removed Special Methods (ther special evetidable _.oex__methods are liste in respective object vite ref, nares.) objet of ase ype already Iilized! (soi Inarge.)> called tna objet wih nara get (20) > called when object willbe destroyed ifdant return a classret abject, then object. Init_ called with intargs Object cast repr (sels) 9s¢stealledforrepe(20lt) and “2012” Ate (aoe) Stes ealed fr ste (oait) and rine #02 Teoerce _(20i,othe=) valu called for oeretoel ect es) Object Hash Key —hash__(001£) 9 nt: hash code fr objec used for bash (ob) and quick ‘mapping keys comparison ~ default implementation use haah (ssl) ‘Attributes access | See also "Descriptors protocol ina getacte (ast, sane) valu, calle or undefined atributer fatteibute _(eeif, nase) 9 value. always called atte (self, sane, value) called for ebj.nenervalue deLacts (2014, sane) called forse obj-nane ash (coe) r082 Be hah code called fr bash) ands Zea (wots, tangs, t#hane) 9 valu calle or 00) ‘Static method / Class method Use standard decorators (see Decorators p3) STS ChaseName felasmmatned 2° methedname (= Descriptors protocol Descriptors are atribute objects contreling access to atibutes values. “They must define some of olowing methods 0b, onazclass} 9 atbute vale fr ob) (aed, ob3, vase) > modify atibute in obj set ovale delete (2012, 003) remove attbute rom obj in these methods sai fs the descriptor abject, and ob; isthe target fbject which attribute |s manipulated. Properties A descriptor to airecty bind methodstunctions to contr! attribute ‘access, Use ulin type pepe with in args ‘atvibutname » property (getter, sete, delete, description) Leach init arg defautefo None fle. undetined). Copying Objects Assignment only duplicate references, To shallow copy an abject (build a Tew one wth same values = referencing same content), of to deep copy {an object (deep-copying reerenced content), see object copy methods, {nd functions In standard module cory copy copy objet vale: shallow copy of obect copy deepcopy (objet; meme), nil) value: deep copy of objet Params mana andasi are used in recursive despeopy, their default values are tone and empty list, Copy Protocol copy__(uolt) > value: shallow copy fs clled by copy copy ‘dnepcopy—0lf,0no) > valu: dep copy of sel clled by copy. deapoopy ..) For copying objects can define pickling protocol too (see les Serialization p12}, in lace of eapy.- 2nd daepeapy Introspection Beyond this documentation, Many some are wtable (see other docs). See standard module snepect to manipulate these data ‘Example of Introspection Atributes I ote: classes are objects too! siete +tupiesallowed objects atributes names! of a class ict dict’ defined abuts (obec namerpace) ofan neance name 9 Str ebject definition name ofa function 21a sting: pathname of loaded module pye-py0 oF pyd [7st oF alowed attributes names, Usage discouraged attributes ae defined, Mooutes ano Packaces Fie gabuzo.py > module gabueo. Directory kramed ath file -init_py > package Keaned. Can have subpackages (subdirectories having init ile Searened in the Python PATH. Current Pytnen PATH stored in sys.path Ist. Contains directories and ip les paths. Bul from location of standard Python modules, FPrtuoubatu environment variable, directory of main module given on Command ne, data spected in lines of th es founa in Python home ‘directory, and data specified in registry under Windows Current ist of loaded modules stored in aya.nodules map (main module isunder key — main) sport mad aa alia on module npo°* name alle reload (module) ® modules loaded (but old references stil on old module Iimpor can use package path (ex:¢rom encoding. aliases snpo°*.) Direct import from a package use defntions from —Inlt_-py “le Very careful witn ingore + a imported names override names already sefined Te limit your modules names exported and visible by :apoct. , deine ‘module global —a11__ with Ist of exported names (or use global ‘See _import__buitin function, sap buitin module and shooks module. —tsport—(modulenamel, global locals names) Source encodings See PEP 263, Declare source files encoding in fist or Second line ina ‘special comment. If this is not specified, Python use aye. getdefauttencoding() value (gee modules shecustomize py and serv Iris important to specly encaging of Your Modules as u ito comecty Build unicode ikerais, Special Attributes £16 _ 9 sving pathname of compiled module leaded Main Execurion / Scrurr PanaMerens ‘The "mai module i the module cales via commandsine (or executed By shell wt rst serge line #1 /bin/env python), commandline parameters are available in sya. ave (a python 2 strings use At end of module, we may have Execution ext after last main module instruction (in mutithread, wat, als for end of nen-daemon threads), uness interactive mode s forced, Can force ext with calling sy ext (code), which raise a Syssenxs ‘exception see Curent Process -Exting (p13). ‘OreRarors: Deal with arithmetic, boolean log, bit level, indexing and slicing, Priority pres yan Sher aay hy ‘Arithmetic Operators can be defined tor any data type, ‘Arithmetic Overniding dd_(eett, other) > valte: calle for self ¢ other fub__(201f,ot80r) 9 vale called forse)? other —mut_eeit,otner) 9 vale called forsee * other atv ooie, other) > value called for selé / othez truediv (seit, other) ‘value called! for sel / other noorsiv_(ae2t,othes) > valu called fr self // ober Imod__{veié, other) > valtecalle for seit ¥ other ivnod{oel£,cther) > vale: called for divaed(eel£, other) pow (20)f, other) 9 value called foreol #* oxo —nonsero (se) vale: called fornoneero (2025) eg (eel!) > valuecaled rset _pon_(emt) + valu calle or se01e | (ue) > value called for aba (0936) fadd__(aelt, other) » called fora? += othor sub__(aelt, other) > called forsale ~= other Saul (anté, othe) > eld foranae #2 thar Jee, other) > called forsee /= other seruediv (dels, cthex) > called! or sels /= other Aslooeaiv _(201t, other) > called fr s01¢ / ined _{oeit, other) > called for sel ¥= other spow__(ee1é, other) > called forsel® *¥~ other Thou with from _ futur impor division Binary operators 1000 have also rex. forms, called when target object on Fant Side Comparison Operators Operators can compare any datatypes Compare values with < >= == te Test objects Identity with -» and {= 20: (compare on (e) Direct composition of comparators i allowed in expressions: xeye Bulkio function emp (o1, 02) > > (01 < 02), (01 == 021, (01 > 02) ‘Comparison Overiing ther) #ocl! clled for sei «other thes) 900147 ealed for soit > othe (thes) >2003!? ealled fr vol > 08 (thes) bool! called fr 20é ‘and for vel © other 2, othes) + nt called for eel compared to other, ‘Any value usable a= boolean value, ora WotTaplemented value if cannot compare with such other type Operators as Functions operators are also defined as functions in standard operator module ‘Comparison ae tab) = 1k 8) ne(a.b) = nea 8) deta.) = te) gela.b) = ge.) gta.) = eat) (3,6) = ot a.) Logical Boolean not fo) = ast (0) and (2,8) = and (2,8) truth te) or tab) = seta.) seria.) se not (a,b) Arithmetic sbe(o) = _abe_(o) exuedev(a,8) = trues (2,6) Sed(a,6) = add (a,b) floordiv(a,8) = floorasw (2,8) 00(a,6) = sub _12,6) neg te) = nego) mul (a/b) = ma pose) = —pos_(e) aivia.b) = aw Pow{a,6) = pow (2/6) edie.) = nod ‘it Level amnsee (a, a Francce (2,6) =_rancee_ (a,b) Snv(o) = savere(o) = tev (0) —tovert_to) Sequences concst (2,6) = _eoneat_(2,b) containe (a,b) =—containa (2,6) ‘ountoe (a8) dene (2 8) epost (2,6) = _repest_(a,b) stem (2, be) = seticen (28,8 getitem{a,s) = getiten (2,6) etitem(a, 8) = —deziten_ (2,5) 1ice(a,8/e = setaisce_(a,be¥) getaiice (a,b,c) = getslice —(a,b,6) dataiion (a,b,c) = daialion—(a,b,e) Type Testing | These functions must be considered as not reliable Astappingtipe te) sesequencetype(o) ‘Attribute and item Lookup aceegetter (ar) 9 fer where fxgoxatr Sanger (tem) fer where feaxitom) ® Boourans False ono, zero numbers, empty containers. 31° > ue if nat false. 0 > 002 (expr) 9Tous | False Logical nat: so: xr Logical and expe so expe Logica or: exprt o= expe? [Cogiea' and and oe ose short path evaluation Bool Cast Overraing |_nonsaro__(aa¢) boo) start object eel TH enonzare. “undefined, look at len. else object struc, Noweens, Bultin integer types: ins {lke C long), 1ong (unlimited integer) Set (expr baze=10}) > ot cattof expr ong expe, base=10}) cr ast of expr Bulla floating point types :s2ce: (like C double), comntex (real and imaginary parts ae #23 on: (exp) oats representation of rer complex) > compen number ers Latlys > conten: number e304) 82) -consugabe{) ounp lin conugate of cample number (real-mg) ‘axiom int integer in sys max ‘Automatic conversions between numeric types ‘Automate conversions fram ine to long when result overiow max it. Direct conversions fran sings lomo int. long. ve types, “ype becins= defined in standard module decimat Base fixed type compact storage arrays in standard module azzay. ‘Operators we te ty wy ty Ady aL yy? ey? With ‘ron future ness division, Is true dlsion (2/20. and // oor division (2// 240). Else for integers / Is stil leo division, 2s remainder operator, ++ Is power elevation operator (same as pow) Functions Some functions in bultins fe a) > abrolte value of asvnodtenn) 9 Gr 8 fet imteger) + 22! cal representation of integer number hx ineger) > cs hevadecia representation of integer number Math Functions andar floating point funcionsidts in standard mata module con) 2 oast radian angle forx conus value: (2.11910. finn) > Leasi radians angle fr x snes value: [-1.A)fon/2.m/2) fsean(x) 9 Loassradans angle for x tangent value: Fu.) +f-m/2-¢/21 fean2 (x,y) 4° ost randane angle for/y tangent value font (x) 9 Cleats amallert negra value» {08 (a) + Eloat cosine vale for radians angte x conh(x) # cLc2"* hyperbolic cosinus value for radian angle Sop) 9 Lonts exponent ote fabs) 9 cLoa"sabsoace vale of Sloor (x) 9 £iost* rgest integra value <= fred (ny) 9 lost: modale~ rmander of x7 Eeaxp (a) > {:loaty 108) my mmanties of xy exponent of — where Aaepa tes 9x82" og ta) 9 £1538: neperian logarithm of ogt0 (a) 9 ioct decimal logarthn of x ode (x) 9 (L05t(2) 1 (sled fraclonal pat | lgned Integr part pow(e 9) 9 cioetexralsed ey power Tinta) “boat: sinus ve for radians angle x fiah(x) $1103"7 hyperbole sna valueforradian ange fget (x) 9 clots square oot of fa) Una) foot: angen vale for rains angle x anh (x) scat: hyperbole tangent value for radians ange + pitt lossrvale of pins. 415976595297950) [Module enath provides similar functions for complex numbers, Random Numbers Randomization functions in standard sandow module, Module functions ge an hidden, shared state, sason type generator (uniform isvibution) Functions also avallable as methods of randor objects (3) > Intaize random number generator Fandon () > £uoetzrandom vale in [010 Fandint (2) 9 intsrandom vale in BI ‘Uniforn (a ) 91 on randam vale if (get candies (4) 20a wth k random bts Fandzange (star, sep, sep) sss random value range (start, st te choke (4g) value random tem rom sequence sheet (x, rade) Pits of x rndomly reordered using mdetO Sample (populations) 9 12%k random lems from polation ‘Akemate random dimbutions “hetavarsate alpha, bets) fexpovaciate ambd), ganmavariate (alphabets), gauss (mi, sma) Aognormvarsate (mu, sigma), sommelvariate (mu sigma) vonmiseavariate (mu, kappa), paretovariste (lbh). wrecbullvarsate pho, bets) Alternate random generator ¥cimannitst> ass Direct generator manipulation :getstate (), ststate (state) Sumpabenda) inmodule os, se oa urandom(n > sc1:m random bytes sutable for enptographl ue Other Math Modules ‘Advanced matrix, algorthms and number crunching in third party modules ike aunarzay /Yuneric (KROWM a5 NUMPY), gmPy (rmukiprecsion arithmetic), Dectas, sespy, See sites SoPy, oP shon, PySesnce, ‘Numbers Casts Overriding sot (sol) 9 nscale for ine(aet¢) ong _{ael) > Lorelle for ong (201) Tense (eee) 9 s0atrcalled for float (2032) ‘complex (016) 9 conplex called for comptex (801) oct (eels) atzealledforoce( ‘hen _{eelt) 9s¢ysealedforbex Teoerea_(ee1f, other) 4 value calle for coaree (461, oth Bir Lever Operations Work with se and isng data Operators cen > hited lot by nbs (eroes inserted) 1220-94 sited ght by m bits eres inserted Binary structures manipulations in standard module st xuct. Advanced binary structures mapping and manipulation I ted party modules: etypes, xatruct, Bit Level Overiing sed (eel other) value for self & other 1E, other) 9 vale'for sel? J other 2E,othee) 4 yahe'for self other (e0is,other) valuefer col? << other (eis othe=) 9 yaluetor seit >> other (ane) value torment and (eels, other) D elled for sel & thas) D elled forse? ‘Sxor (anit, othex) > called oral ~ Aishige (vole, ther) > called forsee cen other —seeniee (soi, otnez) > ealled forsee > Staves Simple quoted "i) 0" or doublequoteg "oo" Use triple [simple|doutle) quotes for multi-nes stings Strings are immutable (once created a sting cannot be modified in place) rings can contaln binary dat, including nul chars (chars of code 0), Stings are sequences, see Indexing (p8) for chars indexation (shclng) ‘and other operations. ee (eode) # char od (ehan + code ste expr) > readable cntual representation of expr =f valle eps (expr) evaluable textual representation of expr if araliable Escape sequences \ bell = wera ta 1 backspace single que ‘eo escape {double quote \s form feea ‘\ Tackslasn \rnewiine ‘oe har By octal aoe value Ve eamiage return St horizental tab ‘And for Unicode stings ‘ina - unicode char by 16 Bits hexadecimal xx value ‘naman Unicode char by 32 bits hexadeclmal maa Value. ‘vimame| = unicode char by name inthe Unicode database. Keep \ escape chars by pefixing sting iteras with 2 (rR) for ‘raw rings (note cannot terminate 3 raw sting with). Unicode strings ‘Quoted as for ars, but with aw (or) prefix before the string: utvoics* Icon mix stings prefas (orm) and. (or) ‘ou must define your source fle encoding so that Python knows how to ‘convert your souree itera strings Into internal unizode sings Untehe (de) > uncoder string of ome unicode char (rd (uicode char) int! unicode code “th char by hexadecimal mh value \Sneatines = Continue string on next ne ‘unicode objet encoding eros) snscodc: unicode tyssmarunicode ste manimum unicode code~fefcomple time option) ‘Unicode Chars Informations Module unicodedata contains informations about Unicade chars roperies, names oakup (ame) > unicode char from ts mame ane (unleh, default) “> s:<:unleode mame - mayralzeYalelssor inci (une, default) 0: decimal va = ay ase AGS (uni etal) > £20: dig vale - may ase Vatuecezor tuner (ich, deft) + £Lcat:rumere valve ~ may aise Valuekeror catagory (unichr) > st:general unicode categery of har Digirect Sonal (unkhr) > str! bar etegory of char may be empty st combining unich) > =2/\: anon eambining cas of char as integer fast seian width (unlel) > st: east azn with ‘nverored unleh) > Lots mirrored property nbd ex 1 If mirored else 0 corposition (nich) > ste: decmposivion mapping, may be empty st nornalizelform, ont) % ste: normal form of string = form in “KC ‘Methods and Functions From bultins (see also oct and hax functions for integers to stings) (5) + Sts numberof care nthe tring Most sting methods are also avalable as functions in the standard string module sveapitalixe() 9 sting with fist char eapitalized Sieenter with cha}) sing centered Si eount (sub, star end) nt! coun sub occurences within star-end 2 decode (encoding|,erort)) unicose:tert decoded ~ ee encodings ‘ancoda (encoding ators ) st osext encoded ~ ree ancodnge Svendawith (sufi, start end) 950 sexpandtabe (tabsize) “string with tabs replaced by spaces 2 eins starter) 900/12 fet of ub thin started $F sndax (eu, start nd) ints offer of sb = may rae Vive S-igalinun() 98001! nom empty string wih al alphanumeric bars! 2 sgaipaa () #5001: non empty string wih al alphabet chars! ‘Scisdigit () 40015 non empty string witha eg chars Fislower() 9001! nom empty string with al lower chars! {isepace () > bool! non empty tring wih al space chars s-istatle() 001: mom empty string with ilecase words! Scisupper() 9001; nom empty string with all upper chars! 5. join Seq) 9 sing: sealofessseqlles+.sealn-2) just (width, ilchar} “ext ting left aioned™ ‘ewes () test string lowered? trap (chars) ring txt with leading care removed replace (old, new, count) “String with coun sts old replaced by new find (sub, star, end) nt/-Islst offset of sub within star-end ‘Eandex (sul, starkend|} 4 int lat offat f sub ~may alee Valued sor unt (width, lear) “rng txt ihe almost eplst (sep, maxsplit)) > [sting rahtmost words delim. by sep? _Eetzsp char) “string with walling chars removed spl (sep ,maspl) 9 [string]: words delimited by sep" split ines (keepend]) > {string} linet startewsth (sufi, start end) 9200 Seip ([ehars)) ating tert ith eadingstraling chars! removed svapeate() 9 ring with care switched Atte) string with wards cptaized! s.tranadate tbl deltechars)) * string cleaned, converted? Sapper () 2 string wpperet™ £515 (wlth) ring: numerte ring with zeroes Ht necersary ‘Tocale dependant or 8 os stings 2 Default charsseparatorilhar is space. 2 For str table must be a sting of 256 chars - See abeing.maketans () For Unicode no deetechars, and tabie must be 3 map" unkade brdinals to unicode orsinals Formating Use § operator between format string and arguments : singtarge Formating string contains 8 (mame!) width). precstonicede If not use (name). >arpe = single value or tuple of values. Fuse tame) arge = mapping with mame as Key. For mapping, arg can be an object with —-get stem __method - see Overrising Mapping Operations (p8. Format char codes signed int. decimal 324 signed int decimal: 324 f unsigned octal: 77< 1 unsigned decimal 5053 f unsigned hexa : =35 X unsigned hexa :7 3 {float polntexp.: 5.255612 float. point exp. 3.2568 E float point dee. :-0-0c00032 Meat point dee. = 0. c000 1 lkew or# ¢ kee ore © Character (2 charstrorcede) aya object format lke zepe obec)» object Format lke ste (obec Templates with string. Zenptate objects. Use common $ syntax: s#>single S frame $name) > value or name tmol= bring. Tonp!ato(emplate ng) tmplesbet ete (mapping. **hwargs) 9 sting tempat fled lmploafe_ subst tute (mapping, **kwargs)) sting: template filed [Cin subclass Template to build your own templating (see doc, sources), See aso modules fornatter, textwrsp Constants dard module #:=sng provide several constants (do nat modi they ‘ate used in string manipulation funetions) and some sir funeions are not available as methods whitespace “$2 whitespace chars (pe tae HHO capwords (2) 9 strap captalize+ Jon Sahat ane (om to) "anation able ben strane rom andto [™Befntion finch dependant Regular Expressions andard module re has @ powerfull regexp engine. See regexp HOWTO ‘at iioJiviw ames pvnonhewtaegex! Use raw string =". notation Seo aso external projects pypareing PLY (Python Lex ace), tpg (Ty Parser Generator Expressions Metacharacters:. * 52 1 yay use escape. > match any character except a newine (incuding newline with ‘Doras option) = > match stat of string (and star of lines with wour=urwe option) > match end of string (and end of lines with wouruzKe option) ‘spe! > match O or mote repetitions of exp (as much as possible) ‘xpre > match 1 or more repetitions of exp (as much as possible) Stee: > match O or Lexpr Sipe? > mateh ice expr: but as few as possible teprss > match ike expr: But as few a5 possible tipr?: > match ike expr but as few a5 possible ‘eprim: ® match m epetiions of expr ‘ep im)n > match from mt ntepettions of expr, missing m default oO and missing n default inte expr) 2 > match ike expr mn: But as few as possible "et" match one char the set defined By ~79 at begining, invert set definition sy chars froma toy ‘e' seetscape sequences for strings 5) SAS chars. and and atthe Begining mater and) cher 2:9 char x Uncuing ener re mesachaaces ‘xprt expt > match expra or expr snor path eval tree) > match expr and ould @ humbered up STifciftallsh tat least one ot sts. char) group match emoty string, mediy options flags for entre expression = see tz 3. % expr) > match expr but dont buld a group "Stnameserpr) > match exprand ould a group rumbered and named (name must be valid Python lentier ame) > match text matched by earer group ramed name Pate > no Match, texts ust a comment “apr mae it match expr but dont consume input Haxpr) > match i doesn't match expr but don't consume input 2 match if current positon is immediatly preceded by a rmateh for fixed length pattern expr + veape! > match current postion is immediat rmaten for fixed length partem expr Thum /name|yesexpr expr! ty to match yesexprif group ‘numname exits, ele try to atch noexpr Escape Sequences fn \nn > match? group number an) where rst m0 00 13 match? char wien octal value 09 (Oe) ‘2 match only at the star of the string > match? emoty sing at beginning or end of a word”? ‘>> match empty string nt at beginning er end of 2 word! ‘> match ehar class cima digit 0" 5 > mate char class non-dige -° > match char class whitespace | \r\n\x\s\v) \5 > match char class non-whitespace |" \r\n\"\s\v) Se match cha class alphanumeric [3-250 -9 2 > mate end ot tring sf MUI\E nis Ae tw \x \\ same as sting escapes Depends on UNICODE fag Depends on LOCALE fag > wen out of char class definition ((=) ly not preceded by @ Flag options quoaecase (x): case insensitive expression - not locale dependant, ocaze (2): make \w (i > locale dependant. vorurraawe (+ and $ match beginngiend of string and tines. Else ~ ‘and s match only beginning and end of string Doras (s): make . match any char inching newline. Else newine ‘exelided, UuNrco0e (0): make \w 6 Ab \2 Unkcode dependant ‘vexuost (x) =ignore whitespaces and make + starting comments (exceat "when space and are escaped orn char cass). ‘Matching and Searching Can use ze functions, or compile expressions into sk» ‘ond Use their methods See Flag Options supra for Nags parameters. seazch (patter, string, lage) chon ject ones scan throught string to sates patter, slag, lags) 320 apse (pater, stingl, manspit-0)» tring): slit ting by occurences of ‘atten maxapt specie remade spt In ast ter fst naa (patter, string lags) > [string] | string) | ind non-overlapping Enaites (pater, sting fags) *terator over [vst hich ject] ~sameae shtpatrn eh, ting count) ing rpc sro mating Substring“ rept a ehatchobec) eur replacement sting pattern may Be sepa pate el rng courte) (ang, =) same a ah 2 Rom stoape (string) > string non alphanamerie backeashed ors objects on! Wy te match sting with Ifyou need to reuse a pattern, compli It onetime fr al pat ee. compte (patter, Mags }92=_ Pattern object pat-natch [sting] os endpos |) same a match function! pat search (string, porendpos)) same ar arch function! pat apie (string maxepl~0) 2 same a ple uncon? ft €sndai2 (string pos, endpes)) same a final function’ pat fsnditer (stig pos, endpes)) same as Mader fanctlon! pst 2ub rp string, count-0})+ same sub function at sub patter, rep, string, cunt) same as sub function Several unctonsimethods return st 0b ject objects ‘maxpazd (tempat) » string: do backslash substation on template (ke sub mathe) wsing match object proupe valves imeqeoup (gaa, =)) stingy (string) subgroups ofthe match from numbers acon)» ang) al nubgrouns of he math = eat imgzoupadce {\defaultoNone) it: names subgroup: ll named subgroups smacaze | group-0) 9sindex of sat of substring matohed by group, Lif mand (igroup-0) 9 crs inder of and of substring matched by group, 1 if imapan lgroup-0)» (812) “values of stare and ond methods forthe Imendpos > £38 endpes value of search/mateh method index # intone: Indes of last matched capturing group 2 Back references extended to \gcgreupnum> and \aearoupname 2 Using par of sting between por and endpos. Group number 0 correspond to enti matching Localization andard module Locale provide posix locale service (Intemationa- ization locale (eategn local!) curent/newsetngs If locale speced ‘tring or tuplelanguage code encoding) mei leat setings for eaegery ocaleconv{)> dicts database oc conventions ‘51 langinto option) sting locale specie inormatins ~ not avaabe on {getdasauiclocate {lenvvart) (language coe, encoding): try to determine get ocate (category) current £2 * setting fr eategory category default {fo £6. CUYPR = fr language code and ancoding it maybe getpreterredencoding do setlcale) >=! user prffered encoding for text dats ~ se do, selocale fo 50 to avoid possible call to zat Locse() ‘normalize (losloname) normalized locale code for leaename usable with esetocaze (category) > reset locale for category to default setting ~ ool (3.42) ot: compare two strings follow LC. COLLATE sting ~ Tiurn Difsknvs2, ONsio92 sensing)» stringrtransform string for local-aware comparison Format (format val, grouping)» sringcamvert va lat slog format ‘peratr conventions) fellow LC HOMERIC stings (eimal pont, + SEE (Lou) sing: conver Moat fellow iC NCMERIC settings decimal, Eo (sing) 9 Loa: convert ng te Moat follow Le NUMERIC stings 04 (string) > nts comvert tring t integer follow 2¢.HERIC aetnge ‘SHAR OX 9 symbole constant used by }oce2econy () Categories “LC_COLLATE + strings sorting - strc011 () and atxxfzm() functions 1C TIME $time formating - tse. steime() {EC MONETARY # monetary values fermating~ options fom ocataconv 1c MESSAGES + messages display - 08st r@rsor()~ not fr Python LE NOMEAIC 4 numbers formatting - format (1, ates () ato€() and ste) ‘thie module (dont mody normal Python mamber formating) 126 ALL all lcaes used to change/rerev he lcae forall a ‘lL Janginfo options a Tago Tae ET fpr ne asaBTe as Tora er SOT ToT Um aT OE fone asable as Yormat or s0PmeD Tor dae [me sable as Yormat or s0fmeD Tor Ue [scree Ra [ ale a Varma for sre Tor Une BR TORT HL ag FOL Wee SE fresexen [regular expression oF library usable Tor Ves DIV Feascrens [currency symbol preceded by — I ahould appear Before Joecteine [Enno wa se a Tora Torsten Tor date Ware Tocaleconv keys [=Sepeney EE [CST TENET yal Yor monetary VAIS [iscsne pont —[becimal point character Tar numbers [Number of racional digits used n focal formatting of monetary values. i081: relative postions of thousands sep" numbers, cxar_yax at the end stop grouping, atthe end repeat last group. inernational currency symbol of monetary valves Number of Facional dais used nt Tormatting of monetary valves [zon cocina socse [Decal point used Tor monetary value [Fauvarent to "Grouping, used for monetary values Tiina sap_|ovoup separator used for monetary values noe_precedes Tue ircurrency symbol preceed negative |monetary valves, fase foiow. Fue i here is a space between cuTeny leymbol and negative monetary value. Position of negative sign for monetary Value Ppot asses anrctate a negtve monetary rue i curancy Symbol praveed postive lmonetary valves, false it ‘olow lsymbol and postive monetary value Position of postive sign for monetary Vale [Symbol used To annotate 2 postive monetary [Character used between groups of Tats Th Possible values o=currency and value surounded by parentheses, 1Stign should precede value and currancy symbol, 2=sign should fellow value and curency symbol, 2-sign shoud immediatly precede value, asin shoula immediately follow value, ue wax=nothing spectfieg inthis locale, -Multingual Support Standard module gettext for interatonalization (I18N) and localization (CON) services based on GNU gettext API + higher interface, See docs for explanations about tools usage Base APi Dbsndeextdomasn (domain) locale} 9st: bounded directory - Bind domain bind textdaaain codeset (domain, codeset) "codes binding bind domain to codeset If specified “change migetert) retuned stings encoding Llewedonain {domain} » glial domain se glebl domain speed and mot gettext (mesage) > string lcaized translation of message ~ bared on gettext (message) 9 sting Ike gettext (), using preferred encoding get cox: (demain, message) sting ike getcex() loking i specified joctext (domain, message) string Ike yet tax (using preferred get cext (singular, plural) string ike got tax (, but consider plural, orm tee Python and GNU getent dos) agate ng, lan) sng: ke age, sng prtered ingen (domain singular) sing the ng) oki in 2adaget nt {dma singular, lars, > sing ke dng ton) ng ancraly is bound to gettext. gettent, and translatable strngs ara written InSources using _(‘thesting'). See docs for usage cxamales (lass based API ‘The recommended way. Module gettext defines a class reansiations, ‘ealing with mo translation files and supporting #=s/ans cose ngs. cd (domal, ocledi,fanguages,alf)}) == /:emo fle mame for, eanslatins (aren fecae language /LC MESSAGES/ domain.) analation (demain locale languages class, alloc, cedeset))> ‘areise ona: objet rom elas ass eau to I)"rania"c0n% onsructer ake ile object ts parameter) =i tre fallback alow to return Ep Reston oa fname le found tah oe e020) snstalt (domain, locale, unicode, codset)) > install_ function in Python’ ulin namespace to ure _(shst 103°) ‘Nut Translations ‘The wulLtsanetetions isa base clas forall anslations. ance (I) Dini tramsaions fo ait object ~ cll parse) i pasa (p) nothing: subclasses override to rend dat from the fle AH taba falback) > ad ia asd canna found anion Derine methods gattaxt, Lgettext, agettext, lagettext as inthe base APL And define speciale methods ugeteext and unget ext returning snicode strings (other forms retum encoded =< stings Retum translated message, forwarding to fallback itis defined Overriden in subclasees emt) return protected sno atibute leharaet() + return protected cha “gut oacnn 0 rtm rete pt_oharaet abate (outpt_charset (charset) > set output charset atbute mate (unicode!) bind bul namespace to selfgettext or ‘etfugatcext 0 upon aniode (default 10 fle) ‘GNU Transations ‘The sxusransiatscns class (subclass of fon GNU gettext and mo files Massages ds and tents are coerced to unicode. Protected nto atvibute contains messagt a) Is based ‘Tansation for empty string return meta-data (see doc Define methods gettext, Lgettexeugettent, agettext, Zngettext, Values (st-/asaeate). Message translations are searched in eatalg, then in fallback if defined, and if ho Wanslation is found, message tell Ss retumed (fr au. methods, etum singular forms f m=” else plural forms) Containers Basic containers kind ‘sequences (ordered collections): 2st, cupsssee, any Merable, ‘mappings (unofdered keyivaive) Sets (unordered collections) ast, frosnse ‘Operations on Containers For strings, items are chars, For mappings, tems are keys item in eater bool: test tem cota! for ear in cataler > Werte var over Het of coats es (container) st eount numberof ems in containe? ‘ae(conzaner) > vale: biggest tem in conainer ‘in (comaner) vale: smallest Rem in container san container) + value’ sum of items ems must be number-compatbe) "for strings test expr fs a substring of sequence, ® Container must provide direct length metnod "no generator Copying Containers Deut containers constructors bulld new container with references to ‘existing objects (shallow copy). To duplicate content too, use standard module copy. See Copying Objects (63) ‘overriding Containers Operations ten (oot) 9 ‘2tscaledforzen (201) [containa (self, stes)* nocl:ealled or stox no) ‘= ael [you can everide erable protocol on contalers too. ‘Sequences Sequences are ordered collections str, unicoce, 1ist, tuple, but er, ‘esonce, array.asray... any user Cass defining sequences interface, oF any iterabie data Lists & Tuples fulkin types 1s and ~spo store sequences of any objects Lists are mutable, tuples are immutable Declare ast ema!) Declare a tuple : (tem) Notes» (> empty Ist ;{)> empty tuple; tem, 32 one tem tuple List (obec) is: ew ist (ast rom obec / duplicate existing) tuple (abject) 20510: neo tuple (ast from object / dupa existing? ange (start tol, tel) > [0], anthmetc progrersion af integers ange (stars se) sas abet gneating atime URES sing alseauence as 2 mapping key, or ensuring tis Inmutabe Use n place of range fo avoid bullaing huge Iss just for indexing ‘Operations on Sequences See Operations on Containers (p8) too. seal + #092 > concatenation of ssl and se@2 sequence * 9-9 concatenation of sequence duplicated tines 19 sequence > concatenation of sequence duplicated tines ue (sequence, cmp, Key. Fevers} 1st new Hist, sered tems rom ‘Later! (fetssauence) >to Hat where (tite) i tue None et = boo! map (ft seen.) 25=¢! ne st where em FU ems of sequences) duce (ft, sequence, ntiaizer) valu: fe applied cumulatively to Sequence tema ff fazer} bhe-) sip (zequence.) > ls" of apes P tuple containe Rem of ach 1 See eration Tools (p9) as replaceme Indexing se index (7) and slice (stp syntax. Indexs 2ero-based. Negative Indexs indexing from end. Default step i >, can use Negative steps, ‘Sub-sequences indoxs between tems. (avoid creating a new list. toms ing ot 2 mf al a Lan [ae [ma 2 [a scing Tadaxs ‘Slice objects Defines index range objects, usable in (1 notation. 21. (start stop ste) 2 Sce object see, sndi.cos (lem) (20°00) tr, stop ste) Ordered sets of data indexed from 0. Members stact, stop, sep ‘Extended Slicing Mutiple slices notation - corresponding to selection in a mut dimension data - can be writen using notation ike Cay mye mn} Elipis rotation can be used to fil multiple missing slices, ike Ua, xyz ee mn 1 See does [Three dos notation ... is replaced internally by E21pais object Operations on mutable sequences Mutable sequences (ex. 1:2) can be mosiied in place. Can use mutable sequence indexing inlet part of assignment to modify its tems" seainden~eepr; seal start: stop] expr: sq. append tem) > add tm at end af zequence Seq-extend othersea) concatenate oterseq at end of sequence Sea. count (expe) 9 ints mumber of expe tems in sequence eq index (expr start, stop) 930A inde of expr emt Seq. insert (nde, tem) > tem inserted at nde feq.eove (expr > remove st exr tem from sequence sea. pop (index) Heme remove and return item at index default 2) seq. everae() > lems reversed in place ‘roq.t0rt (on, kay], cavern) emt sorted i place ~ cap custom ‘comparison fab) real O ey sname of tame atte to Js aeg{inder] > remove tem from sequence ‘he gitar stops rep | remove ems rom sequence ‘overriding Sequences Operations getiten_(20l£, inden!) vale: item at inde, cilled for 201 {inden} ibaa "(anié,sndax’-vaiun)> set tem a index to value, calle for if Lindexdevalue testes! (Gei#, inde value) > remove item andes, called for Get sens (andes only for mutable sequences. » Parameter index can be 9 sce (start stop.step] replace old | getslicesetsice cesice Gan also overide arithmetic operations —_ad_ (concatenation) and ‘mul {repetition ), container operations and abject operations. Marrincs (oicTionanies) Bulkin type 2sce. Store key.value pais. Declare a dtionary > (Aaysxala(,—!) 1 ce (19:48! empty aeionary tik ‘A.ce (#ehwargs) 9200 from named parameters and thelr values {sce (erable 9 ot frm heya) By erable 4st (other) 9% dapat fro anther ome rs fve) operations on Mappings See Operations on Containers (98) too, considering ope ‘hey vale for key? key) =vatve > set ckey] value tol di keri removes dey trom & 4. £combays (iterable, valueson]}¥4i 2 with Keys from terable and alt a cteae() > removes all items roma {ems (19-191 epy of Ist of they, tem) pls aya ()9 1-20: copy of ds st of keys update (otherd) > copy athrd pals into update itrable) > copy theyre) pas into d update (**hwargs) > copy name=value pals nto d aluos (120: copy of ds listo values (et (hey, dea) values dey i keyed lee deal ssn eaunt (key, deta ]) alae keyed st dey)~defva, return ‘ihey) tterttena > Reratr over hey, value) prs 4 Seereeys () erator over keys 1. Leervales() lertor over values 14. pop (hei deta) alan del hey kad etme the corresponding value «4 popitem() > removes and returns an arbitrary they, vale) pl from TMMley doesn't ext, rise Reybeor exception ‘overriding Mapping Operations gat sven (ane, key) > vale for key called for ea Teey] site (201, hey, vole) set value fr key, ale or elf key] evale GGn1en._ (20¢, kay, valun) remove value fr key, called for lel gene hey? I Can aso override container operat Other Mappings For on-alsk mappings, see standard module sneive, and database modules For ordered mappings se is on keys, ons and object operations rd party modules ordaredbict. Sets UUnordered collections of unique items. Frozen sets are immutable once Fronenaat (erable) > rorunsetusing values trom kerable ‘Operations on Sets See Operations on Containers (p8) to. ‘Lesubsot (others) oc]: tests others ‘esuperset (others) >boolstet others == ‘a6 > ade tat at tm) > removes ter fam set [cleaz ) removes altos from (nt forzen set Antersection others) e647 others, ‘union others) Set $v others ce (thers) “24: fx / cx and xtathers] 5 thers» se: fx aes and xecthers] aymmet ic difference (other) $e [x / 5 x0rACothes] 1 oters se: fxs xo ac others] ‘cory () 9 shallow copy o st 4 pda (ierable) ad al vals trom erable to set Raise eyeror object notin et Results rethave same type a5» object (set/*rozenset). ‘Orwer Conrainens Structures, ALconrrins Generally containers follow Python idioms, you can use: tea cone cont, £52 Kem cont ‘Array Standard module arcay provides efficient array of basic types. It uses ‘compact storage for elements of same type Type Coss nL [ctype Tove [a te = Brae Tris Bighed char Ts frsigned char T= far ser} 2 [re unicode char —fanscoae 2 [i Braned sharin 2 [oi unsigned shorn 2 [rs Bioned int see | 2 [2 unsigned int [oo Bigned ong ine [4 | funsigned ong a aT Houble arcay (teliterable) 9 a:2ay: with ypecode Intalied frm erable stenaize > int: bytes sizeof one array data [append (expr) > append item expr end of ray extend (array) > append tems rom anther aay [count (expr) 9 ints mumber of expr ms le aay nex (expr) 9 t= fet index of expr ent Inaert (nde expr) expr em inserted a Index ene expr remove fist expr tem rom array ‘pop lindex}) vale: return and remove te at ndex(efal -1) yerue() > items inary ae reversed Dbuter_4n€0() > (982) curren storage infos addressitems coun Dbyteawap () > swap bytes ofaray ems #rontie (fn) > append nitems red rom rea binary le otiie (> wnt al em tre! binary He? com Sat (ist) > extend ary rom values inst feolige () #stelems ina iat ‘romat eng (2) > extend aray rom values binary bute (tring) vortcing() 9201 ltame in binary representation romunicoda(s) ® extend u'aray fom data in unicode sting ‘touniceda() Sunicodeseonvert Waray tounlede sting irfess tems than needed, get avaliable ones then raise EOFError Jold methods read ana write replaced by romfle and tole Queue Standard module cot tect ons provides queues management equa (erable) # ee: nal from erable [append (ado rg sid of deaue [appaadie fe (1) 24d fo lt she of deque {clear()> remove all ements from deaue extend (erble)> extend right side of deque lexvandie ft (iterable) > extend lft sde ofthe degue ‘pop ten pep and return em fom dequee right side [pople£t() “item: pop and return item frm dequeue eft side (qerotate (a) > rotate deque fom m steps to ight 90 tlt fd Can algo use standard operations on sequences: 3an (@) ‘reversed a), copy .copy (4), copy deepeopy (4), em = 4. at 1 ‘and serialization via picking protocel Priority Queues Standard module weap, Structure a lst asa pianty queue. haapity (x) > tlie traneformed ito heap heappuah (heap item) > push iter onto heap 1esppop (heap tem: pop and return smallest tem from the Reap heapeeplace (heap, newitem) item pop and return smallest tm from he saegest(n ierabl) | largest from erable femal test (n terable) isn smallest tems from terable Sorted List Standard module bssect maintains lists sorted (va basic bisection algo). Sisect 26d (Ut em hl) 0seinde tint em at tos sored seer sgh et em i) onde tert tema ohtnost Dinwct ..) > Alles forbiawct eight.) 8 26E¢ (tte fh) nse iter a leftmost sored poston? ‘ps0zt_zight (ist, tem fel, hi) Diner tem at rightmost sorted pesto! ‘peort(..) > Alas for ingore right) [With tsk previously sores eration Toole Standard module itextoots provides some practical iterators Shan tral) erator over items of several erables (count (start) erator aver integers from start default ©) ‘yoleterable) 9 erator ecting over erable emit predeatefcteam) aise group erable hey) 9 Keatr over hey valugroup! of tems where Teyfetitemishey value default keys entity Liter (predate, erable) 9 erator over ems of erable where precatectitem) is tue ~ Mone predicate iter items being te predcateelitem i false - None predestefiter ems beng fase Siete rte er oneness inde om assonllterable, start, op, ep) erator over Kame ¢ sc! ndexs fom % sep ecb! 1) erator over tuplettoms at same inde rom erables) apant (elject, cowl trate etrning objet over and wer again count mes default nite) starmap (function, lerable) > lerator over fanclon tape tem rom erable) Caxewns a prelcatee, erable) > erator over ene of erable where ‘predesteferttam) x re Le erable) independent erators fom same erable default n=2 "SSroup of tems is Intemaly used muse save tas ist needed ater current eration, Stop at end of shorter iterable 3 Sice parameters cannat be negative “ Sontuse erable out of toe created iterators Dare & Tine Module time Standard module cine defines common functions and data ate & Time Data + Moat time = <-oa: containing seconds trom ‘epoch’ (january 11970, ‘on Unix- See gat sme (0)), with sub-second precision in decimal par ‘tuple time = rsp containing 9 int (see tab ‘struct vine = cuplo/ebject with int atributes (see table) 3 fis pour = oars > (yes) = (sinew + float delay = +103 containing seconds, with sub-second precision DST is ocal time, UTC Is universal (GMT) time, sccept2ayear * [ne] noo!saccep two-digit year values (default), alezone 9 ints offer pas/mep)inzeconds of DST reltely to UTE in ‘seconds ure ony daylight tre [inezone > int! ofset (os/neg) in Seconds lca (Ron DST) timezone canane 4 (s°7(2): ames of lel timezone (on-DS. DSD, Functions sactine tt) st: bull lca tie string fom tuple time o struc. tine) time sncr= 1). bald oct time string from latte second gt ine (secs=) st eck_tine! convert Mea time to UTE struc tine Hocaltime seesa) 9st cuct cine! convert Mea time to DST stuck tie ‘BEEa (1) 9 lat. tne: convert DST uple-time o tut tine to st. time sleep (secs) > executlon suspended during sce (ot delay) times, maybe Tess cpnal extehing maybe more process/threzdsschedling) steeine format /t2") scr: bul me string fom plete or ‘truc.time uring frat sting (able ints) =~ may rate va cok so steptine (ering format) > scract_t nes parce sting using time format! ine (9 ost tme: current UTE ame xan 0 ree tie conversion ale acordngy to emvronman varsle 2 Default format Nea eb Yd KHLSGMS 4. Missing valves default to (1900, 1,1,0,0,0, 0,1,-0), * earam Secs default Curent time, param « fault o local curent Time format strings [> Pspeprat de arate Wary aay TOTTI [is feo ay 100136 [pan oT [is Becona Toa [no fear Rook UST Sana BT [oe EE ay TET TO= SGT —— rr wee 00ST aay base [zr pew T0397 [oe fear Tw eT Leeale language repre Module datetime Standard module dacetne has tools for datetime athmetic, data ‘extraction and manipulation Defines clase vinwdelts, rine, date, det ‘Module timeit ‘andard module tineit has functions to measure processing time of ‘ode. It can be used in scrips (ee docs), or drecty in command ine python -mtimelt nw) (7a) -s' [4 (ch etatement einte PM orepeat=n repeat timer W tmes (default 3) E'S msetupes, executed s once Inialy (default >=) me: Use time. tsme () (deaul except Windows) ¢ /~dlock se time. eieek () (default on Windows) verbose print raw timing Fests may repeat option hy ohn Brit help and ext Other Modules dard module catendas has function See aso third parry module menateTsne. Fuss Normal fle operations use Python ci objects (or etze-ike objects with ‘same Interface). Some funetlans drecly manipulate les path names (strings) Functons mapping lew level OS handlers (mainly these standard os module) use numeric ile descriptors (fa also known as fileno) Raw data use ++ type (can contain any data byte values, incluaing 0}, Fle Objects dard fle ype is bitin £10. t defines the Python file protocol Create a ile - fie flename|, mede='*, Buti) 91416 object ode flags (combinable) =" read, "write new, "=" write append, update, “=” binary, °° universal newine® Butfersize "0 unbuffered, ~ line buffered, >1 around that size (pent) i an alias for et) Default text mode tres to interpret newline sequences in the le 2 Automatically choose newine sequence In CR or L" oF CRLF adapted from ert platform, [Methods and Functions {close (> fle fused and no longer usable f.£stano() 9001 low level le descriptor {ein ()> butters writen team disk deatey() 500%! ideatr les a terminal fxend| size) 9 sr blok of data ead fom fle fotendline() 9 ster next line read trom fl and of ine removed buld calendars. F-zesdiines() > {seng]: Ist of al line read from file endo lines removed ‘f-neek (oft whencen))> modify current pesiion ale whence 0 from feel () 9 intseurent postion in fle Foweite stringy data woe fle foeitel ines lsttstrngs) > data writen ole een of line added) ‘Old method arandL ines replaced by iteration on fle object. For optimized erect access to random ines textes, 88 module Attributes fF nowiines 9207/tup le of se /one: encountered newline chars Low-level Files fase low-level functons are in standard module os. I coreut o clash with bultns with 08. open name. ‘pan fl, age, mode-0777) fl epen le s08 flags intra ~ mode open (fd, made. butsz)) 3. 16rbulld a le connected 6 fd ~ mo bulsize as for bitin open ()+ mede must start with = or oF = ep (a) 9 nf dupa le deserptor (dupa (a, 12) 013, duplicate le descriptor int 42 previously lasing fd coun 1) cle fe descriptor [Eendtdm)9as/read as most n bytes rom fd fle return empty song tend serite fds)» int wie sof le ~ return numberof byes actully -1neek (fd, pos; how) se fle desepter positon ~ how: 0 from sar. fom ssacanync fd) > Mush le daa te dsk~ don't force update metadata (Unb) ‘Enyne 1) force lw lve OS butlers tobe writen truncate (length) > truncate fle descriptor toa most length (Un) pen Flags Constants defined in os module, use bitswise OR (xly|2) to mix them, (ROMY + write only ROKR > read/write (© CaEAT create new fle (remove existing) ©. pe¥we 9 wenn Uni) (0 HOCETY + terminal device file can't become process ty (Unix) (©_NOTNEERI “xnxx Windows) (SHORT. LIVED * mxanen Windom) ©. SEN@ORARY + evens) (0 _skquuNTzAt + nnn iadoms) (OLtexE + axents wndows) Pipes fot standard proces redirection sna pipes, sea Simple Eterm o2-pape() * ((:0012) (2) serete pale fdmasterfsly) of frend! for on mits £o (path; mode-0666)) ® create named plpe path - mode masked out ‘ith umask= don open (Uns) Uses functions on ile descriptors in-memory Files Memory Butter Files Use standard medules storing data in memory fF seringio.fer:09190) Futtesafestce in memory ete (sing data writen to le f.goevaiwe() # stor eurent data writen to fle #21086 ()> fle mo langer usable fee Butler CStringiO Isa compiled (more efficient) version of String for wr ‘Optional argument allows to Buld memory files to reas trom too. Feesteingzo, sr ing-0Alstingl) {xead sizl) 512: Block of data read from We String) ‘Memory Mapped Files (05 level) Standard module map manage memory-mapped files, usable as fle-ke ‘objects and as mutabie stringlike objects, i build 2 memory map mm = snap. aap (filer, length, egname!, acess) windows frm = map. mmap (fen, length, age, re acct) nnd Use an os file descriptor tfrom os.open{) oF from fle-object's ‘L2en0 ()) fora fle opened fer update, Length specty amount of bytes to map, On windows, file may be ‘extended to that length ifs shorter cant be empty, and 0 correspond to maximum length forte fie, ‘Access (keyword param) AccE3s READ (feadonly), xcezs5_ RITE {wrt todd, defo on Windows), or Acc. 2P¥ (apy on (On Windows, tagname allow to identiy different manpings against ‘Same fle (devaut to None). (On Unix, Rags: axe. rarvaze (copy-on-wnite private to process) oF P_SEARED (default). And prot (memory protection mast} PROT READ oF PROT RIZE, defaults PROT READ|PROT WRITE IT USE protsflags params, don't use access param. ‘mm.ciose()> mmap file no onger usable nm. Ein string star=0)) 992: ofse fmm. flu (offset, size) write changes to disk Imm nove dest, se, count) copy dat in fle ‘nm. read size) st blk of data read from map He! nm. road bye (1 2 ext one bye from mma ie! frm. readline ()-42: nex line read from eed of line removed?” ‘nm. toaize nesize) > rable mmap fle resizer thm. soak ote whencex') > modiycarent poston in mma fle sm: rsn{) > in ength othe real ox fle fmmtei {) 9 <:seurent position in mma file Immerse sting) data writen to mma ‘nm. este byte (byte) st of one char ft) data writen 8 map fhe! 1ngi0 and estringio to build fle-ke objects ina | fie stike methods use and move fle seek postion. Files Informations Functions to setget files informations are in os and in oe.patin module, Some in anvts1 module. Constants fags are defined In Standard seat. module, ‘Some functions accessing process environment data (ex. current working directory) are documented In Process section o2-acceas (path, mode) bolster path access with mede using real gid ~ mode in OF, & OF WOH. x OF on rchown(P8th, uid, 94) change pth owner and group (Uns) Se Achows path i, hd change pth ome and group = det allow ons fatat (4) int: sats for fle desrotor oe fatatvts() ovaruse consitshfermatlons about le system “Gutsy fe descrntor id cn stat (path) rat structure abject: fle system informations (Unis) on Satapathy >t sructr bc fe sytem informations ni) - dot os.stat float tines (inewvale) 9 oc: test/st stat function tine on seatvse (path) 9 searvss versie: infomation about fe system “cntining path (nin ime mime) (numbers) = imes=None we current ime a tpatncons (fd, name) 20% / sn ystem configuration information [Bathcont names variable - mame stor int (Uns) Sapatncone path nama / 00: sum congurton formation and fpathcon£ + corresponding Index on host (Unix) Ge vpathvexiate (path) vol: test existing path mo broken symlinks oe path. Lexiati (path 9002 test esting path ~ allow broken symlinks fo2-path.getarine path) Meat ume lst access Une of path fe path. getatine path) lost time lst modifeation time of ath Ga pach, gat ne (path) 9 last tme:reton time (windows) or ast ‘modiiation time cont) of path on:path.getssee (path ot: bytes sizeof path fe fo2-path.Seabs (path) 2001! tes absolute Ge -path. infil (path) ooo: test repular ie (llw symlinks) Ge spath. indir path) 9001s tert exsting retry tallow syminks) fe path Lelia (path) 200%: test symlink fn path Semoun® (path #05: tet mount pont Sa pata. samesiie (path, path?) 900): ter rferto same rea fle ‘umtmacas) cerpath,semeopentsle (41 £29500: test opened fles refer to same rea! ie (anizmace) coaspath, sameatat (stat, sat?) 001: tet sta tuples refer to same fle shit copy (srepath,dstpath) > copy normal ile permission bits Shst 1 -copyaat(seputh dstath)® coy normal ile permission Bits and ‘Stat Structures at_zesult Is retumed by stat and istat functions, usable as a tuple and as object with atvibutes = ree oe, BVT ibe locks aloe OTE TAM Se Sygate er iO Ts retumed by fatetvesand seatves functions, usable variable indexs) and as an object with as a tuple use seat seributes 7 feseesnat —|pcnavas Pee Beas are enon Testing fecriag Pas See SNS aN ae ‘Stat Constants Defined n standard stat module, ‘1390 + 00007 everybody can reads wrtesexecte 15 2X55 + 90001 everybody cam execute he Terminal Operations os. openpty () + (128 (2)-epen pseude-termina pale ‘tamasterfaseve)m(ty) Uni» co eeynane (fd) 9s terminal device associated of (Uni) to setty (fc: tet fle descriptor alk Unt os. tesetpgep fd pa) set proces group Id assecited with terminal os tesetpaep (fd) process group associated with termina fd Uni) See als standard modules tty and pty. For userinterfacecontrl on text terminal, see standard package curses and ts sub-medules Temporary Files Use standard vanprine module. defines several functions to make life ‘easier and more secure, senporecyt tel (modes, bfsie=-1| sufi, pref) Manedtemporaryitel(moden Ww, butsie=-t, sufi, pre, df) 92 1o/fle- keke Temporary? 10 ~ fle visible in fle-syter seatonp suf, pref di, text) (290, 507): ¢fdpath of mew igporaty fe race condi «yet canada escable sseatenp suf, pref ain!) st path of new temporary drctory created wo race condition ~ only erator can read/wrte/search= nol automates gettenppretix{) > at deftl flename prefs fr tmporay fas ‘Other functions in eampeize and oa modules ate Kept for code compatibility, but are considered not enough secured, Also temps and template data in tempétte - nich should not be used directly Path Manipulations Path manipulation functions ar in standard oe.patn module, ‘bepath (path) >=: normalized absolutized pathname DBasenane (path) 902" fle name part of path ‘comonpefix (paths) +150": Tongest common path prefix char-by-char) ‘sznane (path) sts ectry name of pathname Son oath) 951! concatenate path compenents oracene (path) +21: normalize path ease fr platform (ste dee) ormpsth (path) >aersmarmalize path (// / /(h.om windows | ‘reaipat (path) >a canonical path remove symlinks) Can) eps (path > (282729 + split inte then lst pathname componend splssdrave (path) (2212): splint (drive til Splatert (path) > (01:12): split inte reat ox ost Specific Path Data ays getsstenystanencod:ng() > ename of encoding used by system for Following data are In ox and Inox path Directories 02. 24tasr (path) [225] /[snicode) lit names in path erectory~ Without and arbitrary erder~ path string ype + em stings pe on. mkdsz (path), mode=0777)) > crete directory path ~ mode masked out on. makers (pth, mede=0777))> crate dvctory path recursively mode on zmatz(path)> remove rectory path 2 eanovedia (path) > remove decare, recursively walk (tol, tpdowne cc, nerorsNona}) > erable go throught de tnder top, for ach aye tapleerpath names, Menmes)~ nerroetoseron) see doce os:path. walk (path, vs arg) ® cll sitargdemamenames) fr dis rooted “zpath” may modi names heels) te infacnce wale may prefer fo ure Special Flles 08.2 (sre, dst) create hard tink named dst referencing Sr (Une) 2 symlint are, ds) create symbole ink named dt pointing to se (Unis) 08 ako (path, mede=o6es, device) > create FS node te, device special ile named pipe) - mode = permissions | noueiype ~ node type in © PRES, on vminoe(aevce) > int:raw device minor number on makedev {major, miner) compose raw device rom major and minor Copying, Moving, Removing 08. zenove (path > remove ile path (not eatery) on rename (are, dst) rename rte dst ~ om same lesystom- may remove on. renanes (old ew) ® rename old ne recursvly- try to create n-unl snk path > remove fle pth nt clrectory)~ same ax xanove andard module sue provide high level functions on files ang directories copyEite (te dst] copy normal file content - overnite destination copy ts teabs (ore, dst lengtha16kb))> copy e-ik object content by ‘Blocks of lengt size ( eral for BOM. OPFIE_ AF Codece, 80M Li 302s als for BOW OTPLE LE See encoding = Decoding (013) for detalis ab0Ut encoding and errors Serfalization Standard modules pickte and cPsckie (speed up to 1000x) have ‘suppor for data serializaton of objects hierarchies, see Python dacumentation. See also module marahat (read)write of Python data in platform independant binary format but can broke format between releases) Persistence Standard module shetve use picking protocol to store objects in DBM Tes (see p17) and access ther via a dctionnary ike interface mith eysas see ‘pan (enamel, protocol, wrteback, binary) > sony “dagen. o1- ata proc eal ase Configuration Files Standard module contsgracs canfigudation data euses standard tm les to store auctor Values can contain (ane) references which narervazse | moy be expanded using values same section of and start comment lines ‘The module defines three configuration classes with diferent data access level rpraavcontsgtareor (defaults) $ Sowcontt Cprcontigrarses(idefaults) 9 contigrar so Sposafacontsgrarnes ((dtaut)) > Saucon iaPacse Inthe three constructors, defaults 8 dict of option:value for references expansion veux. EHTERPODATION DEPTE + initsmaxracusive depth fr getO hen row ‘Raw Interface rp defauie()41ct default ales for references expansion ‘sections ()(stig] te sectlns in cont (without DEFAULT) f24_section section) madd new section ~ may raise ‘pshas section (Section) 9001: testi section exits ~ cant tes for DEFAULT ‘pceptions (section) (stig) fit options in section ‘rohas_ option (section, option) seis test f scion and option exists ‘mca flname) nae) filename] ty load coauratin dt trom jis fontnge fa) - return names of onde fer ‘eedtp (fl Mlename) > Joa configuration data from £ se option to srng value section - may ‘powesveilebjec) > wet configuration data fle sp zeaove. option (section, option) i001! atu F=f there mas such Ipcvenave. ection (section) co): rtm i-ve I there was such scion ‘pcoptsonetorm option) 2:2: normalled Internal erm ef epton Normal interface p-get (section, option, ral, ars) string: ale for option in section Interpolation expanded unles ras rue ~ vars of adlional eau reference expansion names are processed by optionxsorm() for matching ep seme (sectlon ran ars) | (mame, value) for gvensectlon raw “tnd verso hn etd ‘Safe Interface 1p. 208 (section option vale) > set value sting for section and option Exceptions (excoptscn) For similar fle format supporting nested subsections, see Configob3 config parser. For windows users, standard module _waneea. For texte configs, can use XML to0', and see also tnd party YAML parsers lke Ryan Excerrions Standard exceptions defined in exeaptions module, and avalabe In “current scope, {All exceptions must be subclasses of uxceot on root class. (Use standard exceptions I thelr meaning cortespond to you errors Subclase standard exceptions wnen nesded Standard Exception Classes Systensat —sys.oxt) called Standeraecos bullin exceptions heitanetscbseas —arthmetie errs Assert ionteoe— asso cond, message) falls Rrtvipovesesoe—attnbute setget fall foninensSesor — host system eto = See arg tuple attribute indowsterox — Windows error codes jofeezer—end.otfle with input () oF raw Smput eyosera seercupe — user interrupt (Ct) OW nsiexirror — non-existent sequence index. eysrsor — nonexistent mapping Key tisortror_—nomexistent name in curent scope, Tnooundtocn!teror reference to an unassigned local variable, sotoronceterer — try accessing weaker disposed object Runtinebsror~ (peter defining agshoc subclasses) systenterce —a bug... Python Valuckssor — good type, but bad value sesing — warnings superclass (see Wamings infra) Warnings Wamings must be subcasses ofa ina mt clas, Standard wernsnge module control processing of waming exceptions. warn messages, category, stacklevel) varn_explictt (message, category, ename eno, module, registry) showwazning (message, category, iename nen, He) Formatwarning message category Mena, lise) #ileerwarnings (ation, message, ctegery’, module, inno append) Exceptions Processing sys.exe_sn£0()* (pe, value, tacebac) fr current excepion's Sys-exe_clear() > current exception related informations cleared sys excopthosk (rw fete, value tacebac) called for uneaught ‘sys. Ceaceback Amit +0%: (rw) maximum levels of traceback printed, <0 [SP ione.None None) i no running exception. dard module ezscaback has tools to process and format these informations, Encopinc = Decooinc See also Unicode strings (95) Source encodings (p3) Standard madule codecs provide base support for encoding / decoding ‘data, Thies used for character encodings, but alo for data, Compression (2p, 622) or data representation (ou, hex) See functions, classes and constants fo les encoding In Encoded Files (p12) Module encodings. alsa Tuneans & SyNcHRONIZATION Python threads use ative threads. A global mutex (the GIL) lock Interpreter data during Python vival instructions execution (Is Unlocked during YO a ong computaton in native code). check for {hreed suitening and signal processing is performed st regular interval sys getcheckinterval ()»-s!euren head itching check Intra sys aetehackinterval (interval) > et thread switching check nto |? Expressed in number of Python virtual instruction. Threading Functions Use standard high level module threasing which provides several lasses = Tazeed, 2oea2 (for thread loca storage), ves, cock and Auock (mute), Semaphore and BoudesSerapore, eer, Module thressing also provides functions stavecount (1 ints mumber of curenty active threads CoreeneTaread() areas: curren running tress, fsuinarate ) > (Thre) Wat of active threads settzace func) > instal trace function called before threads run methods prose TNc) ® instal profile function clled before treads run Standard module tneaad supports low evel thread management. Use modules dumy_thread and dummy threading on platforms without martenreading Threads (lass threading, shreas fs used to create new execution path in current process. must be called with keyword arguments. Specly thread code witha callable argee param or by overriding zun method (remember calling inherited —nst__ in subclasses. give arguments in args and lewargs tuple and dict), give a mame fo Went the tread - group Crantly not used (None), the threading. Tread (group, age, name ays wars) thecaze ) > start thread stv (in anther tread) th tun) thread code to execute cal eget if not ovrriden th Son umeut) > wal tenon a met lapsed at delay Uh gettane () "st thread asocated name th eetatane (name) > set thread asocated name inital name se by ass) th Leadive ) 1001" test thread ave (started and rund net terminated) 1h, Sadaenon{) 9001: test tread have daemon fag th sotDacnon (daemon) ® se read daemon flag ~ must be called before intl ain om resting tend Pion proces st on afer | ttvead can't be killed or paused externally by Thread Local Storage Class enceading. Looe: attributes values are thread local ‘Subclass itor Use it as. a namespace Delayed Start Thread (lass exreading. ines Ia subclass of micenc which effectively run ater a speciied Interval from ts star. breading. Tamer (ntervl, uncon, ags=T1,kwaras=(}) ‘Create a timer that il run function with arguments args and keyword arguments kwargs. after interval seconds have passed, ‘Mutual Exclusion Classes theeading.ock and threading. Aiock provide mutual ‘exclusion between threads." doesn allow atread to re-acquie @ Tocc't alrezay owns, soe does (reentrantlock) lock = thronding tock lock = Uhrending.RLock() lock, nequze blocking) *#:00%,orc acquire the lock blocking alse: dont was (iy) & return Fovefieo te ° lock. zelaaze()> unlock previously acquired lock ust release a lock same times as twas acquire. (Good practice to sequtra/reieaae locks I =f") 1y Blocks. For portable inter-process mutex, see third paty slack py module Events (lass exrasding. Event is synchronisation flag with thread blocking ‘mechanism to wat for the fag, ‘evs threading. vent () new event with internal lag sete False vt S08et (14051: vale of even itena Mag ) > set event internal fig to true ~ unlock wating treads ‘it chaas () > et event interna fag Fale svt wast ((Umeout) > wal fr event ineral lag tobe tve- timeout i 2 Tat delay (default te None-ifnte Bocng) ‘Semaphores Classes threading. Sesaphiore and threading. tounsedsensp! rove simple semaphore fo resources counting (withoutwith counter hecking). seon= threading. Semaphore (valu 1) > semaphore wth intial counter return rns Backing flees dont wat fy) & return /23 32 (> release the semaphore free one resource) ‘Condition Variables Class theeading.condit oa allows threads to share state (data) poected via toc Important condilon variables (ock) must be ‘quired when caling wast, notity oF not sfyai2. See Python docs ‘ond = thzeading.Condition(ilek}) > build new conden variable use tse providen och (arch ov Rh ele buds new Succ Cen scssse(*4gn Val: cir co Yar ter care ‘ond. ast (timeout) > wal unt ated or umeout elapred- tious fst ely (default ta None-lfinit Backing) Release cond var lock and walt fork noticationytmeout then re-seuire lek cond. notify () > wake up ane wating tread OF ay) fond. not eyn2() > wake up all waling threads ‘Synchronized Queues Module queue provides a class ove to store data in a synchronized FIFO queue, and two exception classes fui and rey In Blocking ‘ode full @ueue block producers and empty queue black consumers (in ronblecking mode they ralse exceptors). Other organization can be Blt wth subelassing (Gee source for ineernal methods), (7 queue. Gua (massize) > bud new queue Infinite queue matizec=0 {Qogeite (9 intr sine of the quaue = at cal ie (empty (19251 testif queue size Fat al ie {PU item, Blac Heout|)> putin queue - lock canbe trvefaee Timeout canbe i/o delay. May rate Queve. Ful? exception. «put newest (tem) > same as puttem sis) ‘7a (bc, ieout]) + tee removed from queue ~ block canbe tee/ fale, Timeout can be >/flaat delay = may raze evs. Fopey exception 4a.get_nowait > same as gett2i20) Process Current Process Standard module os has toos to et information about and manipulate ‘current process and its environme exiting Normally Python process ext when there is no more non-daemon t running sys-exs¢(args0))> et vi (abort ()> ex vn 3 SIGABRT signal stoma may be handled) Following ext codes are defined in os (Unk) read yetenuxss exception (may Be cate) arg ie sores rer orig eT Se iene ne mare ie eh Be KorER Tao PMR TOR TOTS PT cons nga BIE ‘You can install exit unetions (or normal exit with modu egiater(funeFargs*hargs))® register function tobe called with args and Registered functions are called in reverse order of registration, Bypassed when process's terminated by a signal, an intemal eror, or an Environment Variables get (varame,defaultNone) bt. environment varlale value ‘putea (vamame value) > set environment varlble~ fect ter started Subprocess~ maycaure memory leak re platform documentation) Some functions alse in o2.pat’s ‘expancuser (path 17 path with intial "or "-uzerreplaced ‘xpanavace ring) 92:8 hg with rare aro emeonment Directory, Files, Terminal See also Console & Interactive Inpu¥Output (p2), and Files - Terminal Operations (012) nde (path) change current working directory to path fendi (f)> change current working drctoy to thus represented by le \getewd (9 cr curent working directory (getewss()#urscone: current werking directory nz00t (path) > change process le-system root 9 path (Unis) “imask mask) >t et earree numeric umask and return previous one ctermid() > sts flename of controling termina (Uni) (get ogin(}ecz name of user logged on controling termina! Uni) User, process, group IDs I pie process ig, oa aroup i, la userid (gata) > ot scuren pid ‘gevegia() 92s effective gid Und a3: ele) > st process efectve gl (Uni) (gets) 9 rcs effectve ald Uni) eld) > rat proces afectve wld (Und (getter! gid Unb £533 (id) > se process gid (Unix) (getia() 9 ntscurent proces wd (Une) ue (ul) > st process caren ld (nin) agi id gid > set process real and effective gid (Uni) eeu rd ul) set proceas real and effective uid Uni) getporp > intscurent gi (ed (get goups ) [nt |: lit of supplemental associated gid (Uni) ‘Setgroups (groupe) > sat it of supplemental astolated 9d (Un) setparp (> cal system function? (ne) sgetppsa() #ne all syste function! (Unie) ‘Get P9 (a) >: prcert group of process pid (Omcurret (Une) (eto (pid)> cal system function (Uni) 84 (pl, par set process Pe group te pare (Uni) 1 See manual for semantis Timings, Priority ae () uta cat xt ert: ost. dlay:uer time. system ime children's sca (increment) 92 reice process ~ return new cents (Uns) Memory pack (op) lek program segment inte memory 368 for op ales (Unt) Host oformations steerer (code) +t ror message forthe ror code ‘inane () "sp! cceurent operating sytem Identifiestion (eymame, nodename, ‘eleave version machine fect Uni) aye byteordar +t=: host mattve bye onder big of Little sya.winver 'sc1s version number forestry Keys indows) ye platform 9 sce platform identifi fox 002) Following data are in os andin os. path egpath > az: search path for ov. enectp*() andoe.spavatp#() lnewep 3st! end of ine charts) forte platerm Python Informations aye builtin nodule names + str}: names of modules compiled into Sys envecaon > nt Python versan wth ome dst by byte ye dllhandie 4 st: handle of Python OLL (Windows) sya pean 901 drctry prefs fr platform independant Python les Sye.api_veraion > intsversionef Python CAP ye version sno 9 (\e0(3), 206,300) major minor mera, releselevel iad «release ns pas bot, canicacen Fine Signal Handling Standard module ssgnal. See doc for general rules about signals usage in Python Signal handers are caliable (stgnalnum, stacktame. ‘Lara tie) > Hoa. delay: previous alarm romalning tine = request anew “SIEALAM in ime seconde cancel prvi onetime (Und salar!) fou delay: previous alarm remalning Ue ~ cancel previous alarm ‘unin. get asgna2{signalnum) fe: curent signal handler o SIG IGN SI. or None thunder not installed Yrom Python) paume ()> seep process unt signal recived (Oni) ‘Signa, {signalnum, hander) +f prevous handler for signal (as gets go82) isa nen Panay 31 SPL)" ely cae nin Following signal constants are defined Module also defines signal numbers (Posi examples - runtime definition is platform dependant) SSECIT keyboard iterupt SSEOQUTT ult request from keyboard STCRBE? abort stp slanal SIGRIPE pe wre without reader SSECYSIE stop request rom keyboard SSEOT=IN read an ty while background SSEGT00 wate on ty when background ~ #5ee your platform dacumentation (man 7 signal on Linux) Functions to send signals are in ox module EL (pd sl) kl process pd with sgl sl (Una) \6L3p9 (Pal #1) Kl process group pod wth sonal (Unt) Simple External Process Control Use standard module subprocess. wraps external process creation ‘and control in Pepe objects Child process excepLons raised before ‘executlon are realed in parent pracess, exceptions wil have Shild.tracebach attribute (eting) Note : subprocess tools wil never call /binfsh implicit. fla (sarge, **kwargs) 9 trun command with argument walt or completion, return recede ~ convenient wrapper around: soon obec Use ropon abjects as process contol tools lone, universal newlines=Fase, tartupinfo=None, crestionags=0) ‘args isa svingistof stings {"conmane arg" butsiz like for £sefopen functions ‘recutable can be sed to provide command in place of ar9s(4] [alm stdout and sdercan be £225 to capture fle ana communicate with supprocess preerec is calied just before child process execution ‘ose fas bool force subprocess inverted files to be Closed, except 0 Yond? shatlboo force execution of command throught the shel ‘rd string specify working drectoy to se for subprocess start “nv dcionnary speciy eswronment variables for subprocess Universal newines sransste ll newnes to» (ke mode fr fles) Starupinfo and craalonfags are optional informations for process ‘reabon under Windows rast () 9 intwal for chi proces to trminae return retunco prcommunicate (input-None) + (stdout, ser) send data input strngto postdsut 2s /\s0e: standard output rm chil process i eptured P.ratsrncode 9 ntsc! ell process return code one If nt terminated fn Une -W for subprocess terminated by Signal N Use aumproceas module when possible (cleaner, simpler interface, see ocs for examples). See also external module pexpect ‘Advanced External Process Control See fllowing functions from o= module (exeel (path ach) (Seecte (path arta ‘eesetp ey att al) (sesetpe fle aa alls em” ‘sx0cv path, args) ‘Seacue (path ange nm) ‘execvp le, args) ‘seecvpe (flaps, em) With exec..new program replace curent process (ct dont return). versions use PATH to locate executabie il.’ versions use adit envto setup new program environment. "1! versions use a positioned are," Versions use ist of variable args spawn (mode, path ara!) it spewnte (mode, path az ene) in spswnip (mode, Mle, ar.) = spawnipe (mode fle, ata ens) 9 int spavnv (mode, path args) 9 i0¢ spawnve (mode path ars, ene) 90 spawnvp (mode, fle, args) “nt ‘With spawn. new process Is created. Ipev' versions like for exec. mode's @-nowar® or ®-sowat0, return child pi (Unix) or process nancle (Windows). I mogeis > was, wait child termination and retum iS ext cade (>0} ores ling signal (<0). On Windows mode can be, 2 DERAEN (same as P NOKATT but new process detached from caling process console) or» ovensay (curren process fs replaced), o() > pi fark a child process, return On cil cild pid in parent (Une onupty (9 (i002) (df fork using mew pseude-teminal for eld ~ pd 15 Om chil. child pid In parent = pseude-termina master end (Oni) start tle (path) ® open Me pth as If double soot! test process continued From ajo cont Stop ‘uni WEPsTOPPED (stats) bool: test process stopped Uni) LESLGNALED (stats) $001 test eed on signal Uni reExrTeD (status) #5001: tert process exited via elt2) system all Uni) [REEITETATOS (statu) >in ented a x2 return el parameter Uni) 5200816 (stats) > i: slgna having Stopped process (nO) RESUS (status) se: slgnal having eed process (Unie) Pipes On Process Three functions availabe in popen? module (and in os module where Stdinfsdout return values ae verted) opened bute, mode) > (22 adoustdin: nce cd at Papen Cad use, mode) (8 adowstdin ser: ncaa cn popend (ma, butsz|, mode!) (©! L6H) stoutstderstdn execute ed Where busizes buffer size for VO pipes, and modes “= (binary Streams) or "=" (text streams, default). Param emda sting passed tacos. system on Unix can be a sequence of strings pascea Gracy to tre program without shell intervention (On Unix, popen2 module aso defines Popen' class (used in popent and ‘popeas functions) and 2opens lass (used in popen function) opana (cmd, expirestden, busi) Soper: ced=stell command ‘ciotudestaer=beo! default False) Popend (ome, butize) 9 op0n6 opens and Popend objects have following attributes pol () £20 eid return code of “Lif chit ot terminated Doves (nth return code D.fronchsia 91182 output rom ald stdout and dee for Pop) Papen) ° See also module comends (Uni). XML Processive Several modules to process XML are available. Some with standard SAX ‘and DOM interfaces, ethers wth more Pyshonic interfaces See also third party eye. extension package SAX = Event-driven fase functons in a. sax module rake_paraer(parter_let) >0(5asSer bale rom Art parer salable Paras (flename ostream, conten hand, ro hander) > parse peraedeing(string, content hander, rer handle) parse string using MLReader Interface Defined in amt.sex.xnirender, smlase make parses) ?ctLsesder object paren (zource) > completly parse source ~ source flename or URL o fle- like o nputSoure- input yee sreams (net character streams) pigetontentiandlar|) scovtonstiandiorseurentone Diseucontentitandier (handle) > set current content hander igetDtDuandier() PU TbiandLer:curent one p-setorDgandir (hander) ® zetcurent DTD handler DPigettntstyRasolver() int ivynes vorseurent one DiseeEneseyRavolver (handler) > se current ent resolver pigetcroriandier() #rcorhandies‘eurent one psetsrorsandies (hander) > zt curren eror hander Disetocaie (locale) > rt lacale for error and warninge igetoatuce feturename) 9 current stings for featur! p.setteature (featurenume, value) > st feature value get roperty(erepertyname) * curren setings fr propery? pp sat ropecty (propertname, valu) > et property to value ere is also an sncronentaiParse> subelass interface with Coed (data) > process 2 chunk of data lose () > assume end of document check well formedness, cleanup pzoaet () > after lose prepare new parsing ® property ames n aml. aax. Bander 25 propes Inputsource interface Provide source of data for parser. Isre.sotPubiicrdid) > set publi idensiner Isre.getPubiserdt) Pustcose public dener lure set Syatanid (ld) > set system denier lore get Syatami() “hunicose: system identifier lave netRncoding encoding) > set encoding ~ mut be a tng cc Usresgetncodingt) 93t=/%0% (if unknown) lire sot Bytest ean (byeile) > set input bye stream - ignored i enn() byte stream lave gatcnaracterStroan () > character steam Locator Interface Instances of Locator provide these methods: foe. getcolumnitanber() # nt: column number where curent event ends foe getzineinber) line umber where caren event ends luc, gat pubaiox6() #¢1 publ dneier of arent event oe. get systents() 9222! ystem Mente of caren event ‘Ariributes Interface ‘Also implement parts mapping protocol (copy (), get ()- aw Rey ()- ‘teens (), keys ), and values 0) ai gettengeh() 9 io::number of stebuter bi getienes () > uricotelenamer of atbutes a1 get type (name) typeof atrbute name = normaly *CO8 1 get Value (name) unoode value of atfbute mame ‘AreributesWS interface Also implement Axtrisuves interface, tansi.getValuebyiane (name) unscode: alle of attbute quae name ra get namabyane ame) + (<0) famespace lela fr ans get gitaneByNane namepar) co icodes qualified name for (amespace, Tecsiname) ansi gov aanes ()9 fo cove]: qualied names ofall acbutes ‘ContentHandler Interface Defined in xa. sax. nancies. is metheds are handlers called when parser find XML structures ‘hantDocunantocator(lecatr|® ret leatr fr arigin af document events chatartDocunent {) > beginning of document ‘henaDocunent() ® beginning of document chacarseretsntappsng rts at) > bso refi namespace chandPeatindtappng (prefi) ond of prefi-UR namespace mapping ‘chatartEienent(name, ats) ® start ofan element non-namespace mode ats hasan ce rsincas interface may be reused copy data) ‘hendelenent (name) > end ofan element -non-namespace mede chatarsEienentis (name, qname, as) > start ofan element namespace ‘mode = nare srocaname) = qname raw XML name ~ ars hasan oes ens intrtacetmay be reused ~ copy dita)” gname may Be 82° (upon tatare-namespace proses) ‘chendElenetNS (name, qnume) end ofan element - namespace mede ‘choharactars (content) > character data ~ content ist or Unicode ‘hignorablemniespsce whitespace) > whlespacer ‘chprocessingtnstuction target data) > processing Instruction chakippedentity (mame) > ently net processed DrDHandler terface Defined in x22, sax.handies. its methods are handles called when parser need OTD relative work, dhs yorDhandier ) 997Diandier subcars obact sth. notatsonbec! (name publ, system) > notation declaration th urpacaedentstyoecl (ame, pull yteml deta) > anparsed EntityResoWer interface Defined in xai.sax-nandies. its methods are handlers called when parser need extemal enlity resolution, eratiysncizyhesoives () SEneityResolver netac oblact fr zosolveEntty (publ, system) 222/snputcourca: default return Exceptions Defined in x3. sax module, cnuxceptios (sal exception) Exteassosecest or (mg, excepton Teeter) — invalid XML ShxnotRecoaniredExcept ion (meg exception) exception) ErrorHanaler Interface Defined in x22. e0x.handies. its methods are handles called when parser detect error. Their exception parameters get AxParsesscept on Objects he eytecotianates ()-aberostandter inveraceebect ‘ch.excor exception) ® recovereraBeerer~ pursing wll cominue if method ch. Eataiteror (exception) ® unrecoverable eor~ parsing must stop ‘hrynzning (erceplon) > minor warning = parsing will cntinue if method SAK Utes spe (tal, nities) 2x11 <> escaped - escape other ene replacng ‘unewcape (tal, enttesl) set tanpy ¢ Tey ages unesenped escape ‘ther entities replacing mapping identies (keys) by corresponding stings quotentts (data emits) 2253p ercape + quote sting tobe aed a prepare input source (source, bal) Inpct Sours: source string, Class ssuienscanos isa consensitndtas writing SAX events into an ‘XML document (le. repreduce orginal document Loenerator (out encoding ) > content hander out flee, dau to Class surscecvase Is a defout pass throught events, can be ‘subclassed to modify events on fy before ther processing by application nandle olieciverasee (Base) % events iter Features & Properties Defined in nt.sax. hander, Dont give thelr value, bu thelr meaning ‘namespace processing (se me namespace prefixes). ‘stributes, namespace Ut, loce names ike comments. Peeper dnclaeation handles: option etnin hander fr DID Property cm node" veked DOM node (f OOM erator when paring, eee [can ony be read during parsing (and modified befor). DOM - in-memory Tree Definad in .don. Two function to registeriaccess DOM processors, ‘and some constants agsaver00\inplenantation (name, tat) > ret DOM getbout=plenentet ion name, features)}* DOM implementation - name reatarenameversion- {HEL SAMESEACE 9 UR of HTML namespace HTML 1.0) omimpiementation Inpl-nastoature fesure, version) 50: test for supported festur in an Node Defined in sm.don, class Node Is parent of XML components nodes classes, sno yp8 int ro) im ELEMENT_NODE, AFPREBUPE_NODE, FEX_NOOE, (COATA SECTION NODE, ENEISY NOOK, PROCESSING. INSERUCEION_NOOE, fo.parenttode Nose /\one (a) ~ Name for Ar nodes eateributen Names /\one atbute objects freemen ee ‘next Siting 9oue/one: ) meet node in parents chiéren fchaatodas # (So5e1:() list of submodes Aaatensid 9 Kode/tone: a) last submede Aecaisane 9 sricode/ice: (fo) element name without namespace pref pretax vunicode/iions: ) element namespace prefix ~ may be empty fe nodeNane 9 snicorte/on! () usage Specified In subclasses fenodeVaiue nicode/tisna: fe) asage specified in sublases fo naantersbutea() #00. eet any atibute exatence fe.hasehilNodes() 9001: tee any subrodeenstence .appandensld(newChild) ?new Chi: add new cid node ond of ov sneereBefore (newChild efCid) “ew Chit: ad new child node before ovrencvetitla (old) » old Chile remove 3 subnode: return when no Tanger ured, must eal dC un nk () eureplacechiidnewChld ldChilé) > replace existing subnode with anew evnormlize() > join adjacent ext nodes -elonetode (deep) ose if dep cane subnedes oo ~ return clone Nodetist A sequence of nodes, usable as a Python sequence (maybe modifiable ‘pen imalementstor. fo.stem (i) ioe /ioncrP Rem inthe ist ocumentType Subciass of oe o.dnternal Subset 4 usicode/ane: compet internal subst fom the evn 9 unccode/icnst ime of root element (as given in DOCTYPE) Document Subclass of ode fo-ereatetLenent (tgName) 9 Lone: neb element node> slereatattentNoda (data) >" urert? mew txt node containing data o.ereateComent (dita) 9 Elenert: new commen ode containing date .ereatePocessingiastructon (target data) # lezen! mew? crereatantersbute (name) oan" new atbute node .ceeateAtesbutes(namerpaceURl, qualifedName) +f \cnont: new! ej geben any raghane (game) 26: search ora! fe. gettienentsyTaghanexs (namespaceURl, fecaName) 9¥ode1. 19; seth fara descends ne sere having Mamespace UR and mame 2 New nodes are standalone - you must nsertassociat ‘document pars Element Subclass of soe, ocsggtane Henicode element pe name ith namerpace may contin ou getLenentsbyTagtane (taghame) ose st: kare forall “descendants (deep search) having ype name anarieeByFagianans(namerpaceUR, ocaName) Xoo etch ora aca ep snc ain anespac UN a fe nae evgetatbetbute fattname) > 0. getattibutexode (atmame) 8: fo. getAtceibutens{namespaceUf, lcaName) > uninose:atbute value fo. gekAteesiuteRoden amespaceuR lecaMame) > fe. renoveatteibute attname) ® remeveatbute By mame lgnre missing strenoveAtt eibuteNode (ldAt?) 3 =! remove and return od Att ©. zenovanttribut aN (namespaceU, focaname) D remove aibute by sractateesbute (atime, value) > set stebute tring value ScantAbteiuteNode(newAté) > Actes seatbute from anew 3c ev detAtersbuteNodens (newAte) > ALc: set attribute froma new 5 eveetAtecbutens (ramespaceURl, qrame, value> hesz:se¢ tribute ‘atte Subclass of oa e.nodetype #ACTRIBUTE_ NODE fevnane 2 unicode (re) atibute fll mame ~ may have colons fo ocaitane srcone: (fo) atibute name part afer colons Slpente in icoda? Go) atbute pref part before clone maybe empty NamedNodeMap ‘A mapping of nodes - experimentally usable asa Python mapping. f.aten index) hots atibue at index ~ arbitrary but consistent order comment Subclass of ose, Cannot have subnode e.nodarype #coman® HOSE Text Subciases of wos, Cannot have subnode, Text pat in an element, ‘cDATASection Subclasses of odo, Cannot have subnade. CDATA section ina document, may have multpie COATASection nodes fr one COATA o.nodatype #CDAEA S2CTION NODE Processinginstruction Subciases of vos, Cannot have subnode. Represents a processing instruction inthe XML document: this Inherits fom the Node InterZace Sind cannet ave child nodes ovnodatype # PROCESSING fo. aeget unicode: (to) procesing nsruction content upto frst whitespace Exceptions Python map DOM error codes to exceptions. onasrings:ze8rs — Implementation limit reach Siosarchysequessses— ingore at wrong place ToonSisens — index range eror Trasontsriburores — Att node already used in tree Trvalisaocesste+— paranvoperation Unsupported by object Tnvatidovaractecter character invalid in te context ‘ant madly nade type Invabiastarstee — ty to Use an Undefinediunusabie object Neneopacense — change forbidden in namespace context, NotFourai=r— node don exist referenced context ‘NotSuppostedie~— operationtype unsupported by implementation Sabatahs lounass= no data for this node Sofestsieat font iounsee=—-cant madly objec Syntaxhe>— invaligeillgal string imp. can? migrate nodes between docs DaTasasts, ‘See Python.org wiki or alist of database interface modules. Some intertaces are for extemal DB engines (mySQL. PostgreSQL, BerkeleyO8, SQLite, Metact.) other for pure Python DB engines (gadty, 2008, Kiryase, Buzhua. Generic access to DEM-style DES Standard module any. isa tront-end to some available D8 modules ‘dbbaah (Wbeadh* Berkeley OB), gabe (4GNU dom), (aux dbm) and the slow portable fallback aunmabs, ata stored mn D8M-tyle fe are accessed via a dctonary-ke interface where Keys and values must be v= open (flename, fag, mode) * dctinary-Hike abject: agin = (ead= left)", "frat doesn exist 'n' (reste new empty) ~ ferror-tuple of exception lasses rom DE modules (anydbmerrer..) Uses module wasendl ¢o Identify right DB module for exsting fle For new files, use firs avalable DE module inthe order ofthe lt this is used by shelve module (see Persistence, 912), 1a modules can have specific functons related to thelr backend, see doce Standard DB API for SQL databases Generally modules for SOL databases use the Standard Python Database ‘pl v2 (defined in PEP24), SOR ESS STE Fao {A Informations Tons [PTaR enthded oor eae WHERE ae Parameter as postional values i 3 S6qUe7Cs, 2 Parameters as famed values in aap, Exceptions (standacaberoe) azeing — Important warning ‘eos — a cath ll — problem with interface (not database) *"atateesr — problem wit Gata processing Sherst ionaliese= problem during database operations Progranmnazro* — SQL programming related error Exceptions classes may also be avalable as connection objects ‘ateibutes (optional. ‘Connection connect (de, rer password, host database) ¥Connet son abject Siorhanarionncion cso Mone aor eana) = deta hander “exception lass, exception valu) } (optional messages (> terminate connection may rllbach if net commited) ex comt ()> commit pending transactions ‘er rolibscx()> rolbak pending wansacions (opinnal) (er eurmos () Pew ra0% obfct cursor f-descrsption * (name, Wpecode, display sie, Intern sie, ‘recison, scale, mull.) }/o%0: describe result columns Ghesrorandlas 9 (et fopona) hander for connection errors. ‘rrarhandericonnecon carvan erorcars,errrwaue) = default handle fll ‘wennagen (acento das exception vale) options mestges concount > ints qumber of rows produced/ effected by lest request or rower 901 /icres(eplonl O-based Inde ofthe curser in the result caceallproc (procname|, parameters) (parameters) ~ (optional cll db “oad pracere= insu oo nd nut parameters my have en epced ce cloae ()> core the cursor ‘chaxactte (oper params)) prepare and execute OB requet- param! i “Sequence ora mapping (Ste module pacanctyie variable) ceuvexecutenany (ope, params. seq) Pike execute witha sequence of ‘prams for mutpe vas) ci tetchone ()* (column value...) / None next row of quer result Nene cn Eatchnany (sted) 9 {(eolomn value) net set of rows of query rel, ‘empty ist when no more data avalable- size default to casrayeive fu. fatchal (9 {(eolumm valu): all remaining rows of query esl cirnext()> (column value) “(optlonal next row of query result raises 1) 9 reue(onesoptlona dears results up ce acrolt (yall, modestelative') > (optional) - sera eurzrin corre cu actsnputaszes (sizes) ® predefine memory area for exacuteox “Sprations parameters ~szesofparam size] param sie: Type Object oF Int imax length fs sing param) - param size-None for ne predfinion earactoutputesze sie column) > et column buffer size for fetches of can ster () cursor option abject itself *Metnod _getitea_'s used to get values in params, using position orname, Canuse tuple or dict. or your own class objects with fs iFaent and. iter are defines, cursors are erable, DB types Constructors Date (year month day object old date value ‘ima(hour minute, second) * obec fo held time vale Tinaatamp (year, month, 437 our, minute, kecond) > objet shold ae Data ron ck (tek) 9 obec old dat valu from agen tks valve nok Font scks (Ucks) > object held a Ue vale frm a given UES value Pimeatanptrontcks (teks) # object to hld time stamp vale fram given ‘Binary (sting) 9 objet to holds long binary string value SOL NULL values represented By Python f 8 types Tynecodes SeRING # ting-bared column (CHAR) [BINARY ong binary eam (LONG RAW, BLOBS) ADL » date/time column [20H + row I column (CHAR) Toois Providen with te snake Code bench 22 module tine ‘Toke a look: pyl int, payee, pyrex, preount, Erace2htm (p10)

You might also like