Sunteți pe pagina 1din 159

Effective Python Programming OSCON 2005

Effective Python Programming


Effective Python Programming OSCON 2005
Effective Programming

Get the job done

Better, more maintainabe code

!"e the ang#age$" "trength"

Python i" not%



C&&

'ava

Per

(((
Effective Python Programming OSCON 2005
)a*ine""

+n deveo,ment, a*ine"" can be good

-o thing" right the fir"t time

-on$t re.invent every /hee

-eath to N+0
Effective Python Programming OSCON 2005
Effective 12 Efficient

Effective doe" not nece""ariy mean


efficient

O,timi"e for deveo,ment time

3hen /orry abo#t ,erformance

4e$ to#ch on efficient code, ater


Effective Python Programming OSCON 2005
3arget

Python 2(5

CPython
Effective Python Programming OSCON 2005
Python 6#ndamenta"

)earning by tin7ering

Everything$" an object

Name",ace"

E86P

-#c7 3y,ing
Effective Python Programming OSCON 2005
Short 8ttention S,an 3heatre

9ey thing" to remember

Even if yo# "ee, thro#gh the re"t,


yo#$ "ti get "omething
Effective Python Programming OSCON 2005
S(8(S( 3heatre

:#e ;<% -ictionarie"

:#e ;2% See :#e ;<


Effective Python Programming OSCON 2005
Programming /ith the hood #,

+ntro",ection

E=,erimentation
Effective Python Programming OSCON 2005
+nteractive Python

bonanza% python

Python 2.4.1 (#2, Mar 30 2005, 21:51:10)

[GCC 3.3.5 (Deban 1:3.3.5!"#b#nt#2)$ on %n#&2

'ype (he%p(, ()opyr*ht(, ()re+t,( or (%)en,e( ...

---

Effective Python Programming OSCON 2005
he, and dir

he,>obj? format" doc"tring"

dir>obj? "ho/" attrib#te"


Effective Python Programming OSCON 2005
he,

--- .port o,

--- he%p(o,.popen)

/e%p on b#%t!n 0#n)ton popen n .o+#%e po,&:


popen(...)

popen()o..an+ [, .o+e12r2 [, b#0,ze$$) !- ppe


3pen a ppe to40ro. a )o..an+ ret#rnn* a 0%e
ob5e)t.

Effective Python Programming OSCON 2005
he,(((

--- he%p(")

/e%p on nt ob5e)t:


)%a,, nt(ob5e)t)

6 nt(&[, ba,e$) !- nte*er

6

6 Con7ert a ,trn* or n#.ber to an nte*er, 0

6 po,,b%e. 8 0%oatn* pont ar*#.ent 9%% be

6 tr#n)ate+ to9ar+, zero (th, +oe, not n)%#+e a

6 ,trn* repre,entaton o0 a 0%oatn* pont

6 n#.ber:) ;hen )on7ertn* a ,trn*, #,e

6 the optona% ba,e. <t , an error to ,#pp%y a
Effective Python Programming OSCON 2005
dir


--- .port popen2

--- +r(popen2)

[2M8=>D2, 2Popen32, 2Popen42, 2??a%%??2,
2??b#%tn,??2, 2??+o)??2, 2??0%e??2, 2??na.e??2,
2?a)t7e2, 2?)%ean#p2, 2?te,t2, 2o,2, 2popen22,
2popen32, 2popen42, 2,y,2$

Effective Python Programming OSCON 2005
Everything i" an object

int", "tring", fie"

f#nction", mod#e", ca""e"

@ariabe" are j#"t abe"


Effective Python Programming OSCON 2005
Object" v" Name"

@ariabe" are reference"

'#"t a name referring to an object

Stored in a name",ace

>defa#t" to the oca name",ace?
Effective Python Programming OSCON 2005
Name",ace"(((

Name",ace" are dictionarie"1



--- .port ,y,

--- +e0 0oo(a11, b12):

... ) 1 (he%%o(

... prnt ,y,.?*et0ra.e().0?%o)a%,

...

---

--- 0oo(a14)

@2a2: 4, 2)2: 2he%%o2, 2b2: 2A

Effective Python Programming OSCON 2005
Name",ace oo7#, Ca""ic

oca"

mod#e goba"

b#it.in"
Effective Python Programming OSCON 2005
8""ignment

8""ignment goe" to oca name",ace

!ne"" $goba$ "tatement


Effective Python Programming OSCON 2005
goba

goba ony for a""ignment

not needed for getting a va#e

goba" are "o/er1


Effective Python Programming OSCON 2005
Name",ace" ne"ted "co,e"

"taticay ne"ted "co,e"



>ne"ted f#nction definition"?

#"ef# for ambda%



+e0 )reateBp+ater(,e%0):

ret#rn %a.b+a 0oo, bar: ,e%0.#p+ate(0oo,bar)

ne"ted f#nction ca"



e=am,e ater of thi"
Effective Python Programming OSCON 2005
E86P

Ea"ier to 8"7 6orgivene"" than


Permi""ion

@ery ba"ic Python conce,t


Effective Python Programming OSCON 2005
Permi""ion(((

Permi""ion%

0 ha,attr(ob5, 27a%#e2):

7a%#e 1 ob5.7a%#e

e%,e:

7a%#e 1 Cone

6orgivene""%

try:

rea+ 1 ob5.7a%#e

e&)ept 8ttrb#teDrror:

7a%#e 1 Cone
Effective Python Programming OSCON 2005
E86P

E=ce,tion" are e=,en"ive

Chec7" can a"o be e=,en"ive

Ca"e.by.ca"e ho/ often i" it e=,ected


to faiA
Effective Python Programming OSCON 2005
Python 3y,ing

4ea7 v" Strong

Static v" -ynamic

C&&B'ava% "trong "tatic ty,ing

Python% "trong dynamic ty,ing


Effective Python Programming OSCON 2005
-#c7.3y,ing

4a7" i7e a d#c7

((( C#ac7" i7e a d#c7

((( it$" a d#c7


Effective Python Programming OSCON 2005
-#c7.3y,ing

6ie.i7e object"

Dight ony need $read>?$


Effective Python Programming OSCON 2005
-#c7.3y,ing 6ie object"

+e0 *etData(ob5):

+ata 1 ob5.rea+()

prnt +ata

0 1 open(20%e.t&t2)

*etData(0)

8ct#ay, that data fie /a" g*i,,ed%



.port *zp

0 1 *zp.Gzp>%e(20%e.t&t.*z2)

*etData(0)




Effective Python Programming OSCON 2005
Dore -#c7.3y,ing

3he ma,,ing interface >dictionary?

Start /ith a dictionary

Sot in a different im,ementation

e(g( net/or7, databa"e, (((


Effective Python Programming OSCON 2005
+nterface"

*o,e(interface

PyProtoco"

8""ert that an object im,ement" an


interface

-oc#mentation

8da,tation

6#t#re Python
Effective Python Programming OSCON 2005
Str#ct#red Programming
Effective Python Programming OSCON 2005
Contro 6o/

+terator"

Generator"

forBe"e

tryBfinay

tryBe=ce,tBe"e

"/itch "tatement
Effective Python Programming OSCON 2005
S(8(S( 3heatre1

en#merate

0or n n ran*e(%en(,eE#en)e)):

e%e.ent 1 ,eE#en)e[n$

in"tead%

0or n, e%e.ent n en#.erate(,eE#en)e):

en#merate ret#rn" an iterator



--- prnt en#.erate([$)

Fen#.erate ob5e)t at 0&bG+041")-

Effective Python Programming OSCON 2005
Ba"ic contro fo/

/hie

for

tryBe=ce,t
Effective Python Programming OSCON 2005
+terator"

:et#rn" the ne=t item each time

No need to have a item" in memory

Dore fe=ibe
Effective Python Programming OSCON 2005
6ie" are iterator"

:et#rn" a ine

--- 0or %ne n open(24et)4re,o%7.)on02):

... prnt (*ot %ne 2%,2(%(%ne.,trp())

...

*ot %ne 2na.e,er7er 210.15.254.2402

*ot %ne 2na.e,er7er 210.15.254.2412

*ot %ne 2na.e,er7er 203.10.110.1012

*ot %ne 2na.e,er7er 203.1G.103.12

Effective Python Programming OSCON 2005
Creating iterator"

iter>? b#it.in

t#rn" a "eC#ence into an iterator

ca""e" can have an EEiterEE method


that ret#rn" an iterator
Effective Python Programming OSCON 2005
Dore fe=ibe for oo,"

Ca (ne=t>? to get the ne=t item




terob5 1 ter(,eE#en)e)

0or te. n terob5:

0 te. 11 2e&ten+e+2:

te. 1 te. H terob5.ne&t()

Effective Python Programming OSCON 2005
3o7en "tream"

toIen,1[2te&t:he%%o2,2,ty%e:bo%+2,2te&t:9or%+2,
2te&t:*oo+bye2,2,ty%e:ta%)2,2te&t:9or%+2$

toIen, 1 ter(toIen,)

0or toI n toIen,:

9hat,7a%#e 1 toI.,p%t(2:2,1)

0 9hat 11 2te&t2:

han+%eP%an'oIen(7a%#e)

e%0 9hat 11 2,ty%e2:

9hat, 7a%#e 1 toI.ne&t().,p%t(2:2, 1)

0 ,ty%e 11 2bo%+2:

han+%eJo%+'oIen(7a%#e)

e%0 ,ty%e 11 2ta%)2:

han+%e<ta%)'oIen(7a%#e)
Effective Python Programming OSCON 2005
P#"h +terator

Sometime" yo# /ant to chec7 the ne=t


item, b#t not a/ay" con"#me it

P#"h it bac7 onto the iterator1

)i7e "tdio$" getc>?B#ngetc>?


Effective Python Programming OSCON 2005
P#"h +terator

)%a,, P#,h<terator:

+e0 ??nt??(,e%0, ter):

,e%0.ter 1 ter

,e%0.p#,he+ 1 [$

+e0 p#,h(,e%0, 7a%#e):

,e%0.p#,he+.appen+(7a%#e)

+e0 ne&t(,e%0):

0 ,e%0.p#,he+:

ret#rn ,e%0.p#,he+.pop()

e%,e:

ret#rn ,e%0.ter.ne&t()

+e0 ??ter??(,e%0):

ret#rn ,e%0
Effective Python Programming OSCON 2005
Pee7 +terator

Sibing to P#"h+terator

Pee7 at the ne=t re"#t >/itho#t


con"#ming it?
Effective Python Programming OSCON 2005
itertoo"

high ,erformance iterator mani,#ation

f#nctiona ,rogramming
Effective Python Programming OSCON 2005
Generator"

FGood arti"t" co,y, great arti"t" "teaG


. Pica""o

Stoen from +con

f#nction" containing $yied$ are a


generator

4hen caed, ret#rn" a generator object

((( /hich i" an iterator


Effective Python Programming OSCON 2005
Generator"

$yied$ ,a""e" a re"#t to the caer

e=ec#tion i" "#",ended

/hen ne=t>? i" caed again, re"#me"


/here it eft off
Effective Python Programming OSCON 2005
Generator"

--- +e0 ,E#are,(,tart11):

... 9h%e 'r#e:

... ye%+ ,tart K ,tart

... ,tart H1 1
...

--- ,E 1 ,E#are,(4)

--- ,E

F*enerator ob5e)t at 0&bG+0440)-

--- ,E.ne&t()

1L

--- ,E.ne&t()

25

Effective Python Programming OSCON 2005
Generator"

fini"h /hen they fa off the end

or $ret#rn$

Generator" can$t $ret#rn$ a va#e

Generator" can be caed m#ti,e time"


Effective Python Programming OSCON 2005
D#ti,e Generator Ca"

--- ,1 1 ,E#are,(5)

--- ,2 1 ,E#are,(15)

--- prnt ,1.ne&t(), ,2.ne&t(), ,1.ne&t(), ,2.ne&t()

25 225 3L 25L
Effective Python Programming OSCON 2005
Generator E=am,e

-B.8P+

c#r"or(fetchone>? . get one ro/



+nefficient1

c#r"or(fetcha>? . get a ro/"



Co#d con"#me a ot of memory

c#r"or(fetchmany>N? get N ro/"



Sighty fiddy
Effective Python Programming OSCON 2005
Po""ibe So#tion"

0or ro9 n )#r,or.0et)ha%%():

pro)e,,Me,#%t(ro9)


ro9 1 )#r,or.0et)hone()

9h%e ro9:

pro)e,,Me,#%t(ro9)

ro9 1 )#r,or.0et)hone()


9h%e 'r#e:

ro9, 1 )#r,or.0et)h.any(100)

0 not ro9,:

breaI

0or ro9 n ro9,:

pro)e,,Me,#%t(ro9)
Effective Python Programming OSCON 2005
Generator @er"ion

+e0 Me,#%t<ter()#r,or, array,ze11000):

9h%e 'r#e:

re,#%t, 1 )#r,or.0et)h.any(array,ze)

0 not re,#%t,:

breaI

0or re,#%t n re,#%t,:

ye%+ re,#%t

!"ing thi"%

0or re, n Me,#%t<ter()#r,or):

pro)e,,Mo9(re,)

Effective Python Programming OSCON 2005
forBe"e

for "tatement" can have an e"e% ca#"e

e=ec#ted /hen the for oo, e=ha#"t"


it$" oo, >no $brea7$, ret#rn or
e=ce,tion?
Effective Python Programming OSCON 2005
forBe"e e=am,e


0or e%e.ent n ,eE#en)e:

0 e%e.entMat)he+(e%e.ent):

)orre)t 1 e%e.ent

breaI

e%,e:

prnt (no e%e.ent, .at)he+(

)orre)t 1 Cone

Effective Python Programming OSCON 2005
tryBfinay

finay% ca#"e i" a/ay" e=ec#ted

re"o#rce cean#,

%o)I 1 a)E#reNo)I()

try:

7a% 1 +oOo.eOt#00()

0 7a% , Cone:

ra,e Pa%#eDrror(2*ot Cone2)

e%0 7a% F 0:

ret#rn

0na%%y:

%o)I.re%ea,e()
Effective Python Programming OSCON 2005
tryBfinay

Great for ,reventing tho"e nightmare


b#g"

F3hi" "ho#d never ha,,enG

Chance" are it /i

Program -efen"ivey

3he !niver"e 0ate" Ho#(

4oef#y #nder#"ed
Effective Python Programming OSCON 2005
tryBe=ce,tBe"e

tryBe=ce,t can have an e"e% "tatement

e=ec#ted /hen no e=ce,tion occ#rred


Effective Python Programming OSCON 2005
tryBe=ce,tBe"e

P#t ony the im,ortant bit" in the try%


boc7

try:

.port *tI

e&)ept:

My;n+o9 1 Cone

e%,e:

My;n+o9 1 *tI.;n+o9()
Effective Python Programming OSCON 2005
minimi"ing code in a try% boc7

3hi" code ha" a ,robem%



try:

+ata 1 ob5.rea+()

e&)ept 8ttrb#teDrror:

+ata 1 22

3hi" ma"7" any 8ttrib#teError" in the


read>? method

So#rce of hard.to.find b#g"


Effective Python Programming OSCON 2005
"/itch "tatement

,ython ha" no "/itchBca"e

ifBeifBeifBeifBe"e

#"e a dictionary
Effective Python Programming OSCON 2005
-i",atch via dict

0 n+ata 11 2>3QQ<D2:

,ho9>ozze()

e%0 n+ata 11 2RDMM<'2:

,ho9Rer.t()

...

e%,e:

,ho9BnIno9nM#ppet()

become"%

)a%%D)t 1 @ 2>3QQ<D2: ,ho9>ozze,

2RDMM<'2: ,ho9Rer.t,

... A

0#n) 1 )a%%D)t.*et(n+ata, ,ho9BnIno9nM#ppet)

0#n)()
Effective Python Programming OSCON 2005
Object Oriented Programming
Effective Python Programming OSCON 2005
!"ing Ca""e" Pythonicay

Ne/."tye v" Od."tye

Dore -#c7"1

i"in"tance

inheritance, mi=in"

acce"" contro

Sim,ifying yo#r 8P+"


Effective Python Programming OSCON 2005
S(8(S( 3heatre

EEdeEE i" not yo#r friend


Effective Python Programming OSCON 2005
EEdeEE often con"idered harmf#

C&&B'ava.i"m

EEdeEE brea7" garbage coector

non.determini"tic

doe"n$t a/ay" get caed #"ef#y /hen


Python i" e=iting

#"e a /ea7ref in "ome ca"e"


Effective Python Programming OSCON 2005
Ne/."tye v" Od."tye

Python ha" t/o ty,e" of ca""

Od."tye ca""e" are the origina one"

Ne/."tye >in 2(2? fi= i""#e" /ith the"e



-ifference bet/een C ty,e" and Python
ca""e"

Can inherit from b#it.in ty,e" >e(g( dict?

Some "hiny ne/ feat#re"
Effective Python Programming OSCON 2005
Ne/."tye v" Od."tye

Ne/ "tye derive from $object$

Ne/ "tye ca""e" in 2(2

6i= for im,ementation i""#e" in origina


ca""e"

Dany ne/ feat#re"



,ro,ertie"

de"cri,tor"

EEne/EE

(((((
Effective Python Programming OSCON 2005
!"e Ne/ Stye Ca""e"

Do"t ne/ code "ho#d #"e them

4i become the defa#t in Python I(0


Effective Python Programming OSCON 2005
Dore -#c7"1

Object" "#,,orting the ma,,ing


interface%

dictionarie"

Jdbm databa"e fie"

"heve"

dbEro/ in"tance"
Effective Python Programming OSCON 2005
Sometime" yo# care

3here are time" /hen yo# care /hat


thing" are ,a""ed

Chec7 for the method" yo# need



0 ha,attr(ob5, 2rea+2):

ob5.rea+()

e%,e:

ra,e Pa%#eDrror

Or #"e an +nterface
Effective Python Programming OSCON 2005
+nterface"

-oc#mentation

8""ertion"

+e0 *et8#+o>ro.Oo#r)e(ob5):

0 not <8#+o(ob5):

ra,e Pa%#eDrror(2e&pe)te+ a#+o, *ot %r2%
ob5)

ret#rn a#+o.rea+()

8da,tation

8#tomaticay ada,t an +6oo to an +Bar
Effective Python Programming OSCON 2005
+nterface E=am,e

)%a,, <8#+o(<nter0a)e):

222No9%e7e% nter0a)e to a#+o ,o#r)e4,nI.222

+e0 )%o,e():

222C%o,e the #n+er%yn* a#+o +e7)e222

+e0 reopen():

222Meopen a )%o,e+ a#+o +e7)e222

+e0 ,3pen():

222Met#rn 'r#e 0 #n+er%yn* a#+o open222

+e0 rea+():

222Met#rn a pa)Iet o0 a#+o 0ro. +e7)e.222

+e0 9rte(+ata):

222;rte a#+o to +e7)e.222
Effective Python Programming OSCON 2005
!"ing an +nterface

)%a,, 8NO88#+o(ob5e)t):

.p%e.ent,(<8#+o)

+e0 reopen(,e%0):

....

+e0 )%o,e(,e%0):

....

+e0 ,3pen(,e%0):

....


a%,a 1 8NO88#+o()

<8#+o..p%e.ente+Jy(a%,a)

<8#+o(a%,a)
Effective Python Programming OSCON 2005
+nterface" are dynamic

+nterface" can be changed at r#ntime

8""ert that a I
rd
,arty object
im,ement" an interface

:egi"ter an ada,ter from one +nterface


to another
Effective Python Programming OSCON 2005
i"in"tance

Chec7ing obj(EEca""EE i" evi

Brea7" "#bca""ing

ty,e>foo? i" ancient, and c#n7y

!"e i"in"tance%

0 ,n,tan)e(n#., ba,e,trn*):

n#. 1 nt(n#.)

0 not ,n,tan)e(thn*, (nt, 0%oat)):

ra,e Pa%#eDrror(2e&pe)te+ a n#.ber2)
Effective Python Programming OSCON 2005
inheritance, mi=in"

D#ti,e inheritance i" #"ef#

Di=in ca""e" a""embe com,onent"


into a ca""

Seect from m#ti,e im,ementation"


Effective Python Programming OSCON 2005
+nheritance

F6at i" better than ne"tedG

E=ce""ive inheritance tree" are ,ainf#

!"e inheritance /hen yo# need it


Effective Python Programming OSCON 2005
-e"ign for "#bca""ing

!"e "ef(EEca""EE in"tead of hardcoded


ca"" name"

)%a,, <te.:

+e0 ??nt??(,e%0, 7a%#e):

,e%0.7a%#e 1 7a%#e

+e0 *etCe&t<te.(,e%0):

ne9<te. 1 ,e%0.??)%a,,??()

ne9<te..7a%#e 1 ,e%0.7a%#e H 1
Effective Python Programming OSCON 2005
Ba"e ca"" method"

Ca ba"e ca"" method" from


"#bca""ed method"1

Protect" yo# if ,arent ca"" change"

Partic#ary im,ortant for ??nt??




)%a,, MonIey(O.an):

+e0 ??nt??(,e%0, banana,12, Kar*,, KKI9ar*,):

,e%0.banana, 1 banana,

O.an.??nt??(,e%0, Kar*,, KKI9ar*,)
Effective Python Programming OSCON 2005
-on$t 8""#me Ho# 9no/ Be"t

Ho# don$t 7no/ ho/ ,eo,e /i need to


#"e yo#r code

3hin7 abo#t ho/ "omeone co#d e=tend


yo#r ca""e"

-e"ign ca""e" accordingy

-oc#ment the method"

6actor o#t the #"ef# bit"


Effective Python Programming OSCON 2005
acce"" contro

8nother C&&B'ava.i"m

friend, ,#bic, ,rivate, (((

Python% FEveryone$" a con"enting


ad#tG

Convention% eading #nder"core "igna"


Fim,ementation detaiG

Better yet% doc#ment the 8P+ of the


ca""
Effective Python Programming OSCON 2005
??,rivate name"

eading do#be #nder"core mange"


name"

+n theory #"ef# to "to, ,eo,e "te,,ing


on im,ementation detai"

+n ,ractice, annoying

Per"ona goa for 2(5 i" to remove a #"e
from the "tdib
Effective Python Programming OSCON 2005
Sim,ifying yo#r 8P+"

-amien Con/ay$" FS#fficienty


8dvanced DagicG

B#t not C#ite that advanced(((


Effective Python Programming OSCON 2005
Container object

Get the object" in a container

6ir"t attem,t%

0or )h%+ n )ontaner.*etCh%+ren():

+oOo.ethn*;th3b5e)t()h%+)

!nnece""ary 8P+

Python aready ha" a good /ay to ",e


thi"%

0or )h%+ n )ontaner:

+oOo.ethn*;th3b5e)t()h%+)
Effective Python Programming OSCON 2005
Container e=am,e

!"ing the iterator ,rotoco



)%a,, Contaner(ob5e)t):

+e0 ??nt??(,e%0, K)h%+ren):

,e%0.)h%+ren 1 )h%+ren

+e0 ??ter??(,e%0):

ret#rn ter(,e%0.)h%+ren)


)ont 1 Contaner(1,2,3,4,5)

0or ) n )ont:

prnt )
Effective Python Programming OSCON 2005
??,pe)a%?? method"

!"ed to im,ement o,erator"

E=am,e"%

??,tr?? ! ,trn* repre,entaton

??,ette.?? !

ob5[Iey$ 1 7a% 22K ob5.??,ette.??(Iey,7a%)

??a++?? ! a++ ,o.ethn* to th, ob5e)t

??*etattr?? ! *et an attrb#te o0 th, ob5e)t

??eE?? ! ob5e)t , ben* )o.pare+ to another
Effective Python Programming OSCON 2005
",ecia method", e=am,e"

8 & B

6ir"t trie" 8(EEaddEE>B?

3hen B(EEraddEE>8?

>4e$re ignoring EEcoerceEE?

8 22 B

+n order% 8(EEeCEE>B?, B(EEeCEE>8?,
8(EEcm,EE>B?, and then B(EEcm,EE>8?
Effective Python Programming OSCON 2005
Da7e the 8P+ +nt#itive

Every ne/ method name i" "omething


that ha" to be

remembered

doc#mented

6inite amo#nt of brain ",ace

!"e int#itive o,erator"

B#t don$t get too cever


Effective Python Programming OSCON 2005
C&&."tye co#t

8 bit too magica to be recommended%



)%a,, Cpp>%e:

+e0 ??nt??(,e%0, 0p):

,e%0.0p 1 0p

+e0 ??%,h0t??(,e%0, ,o.eob5):

,e%0.0p.9rte(,tr(,o.eob5))

ret#rn ,e%0


.port ,y,

)o#t 1 Cpp>%e(,y,.,t+o#t)

)o#t FF (he%%oS FF T9or%+Un(
Effective Python Programming OSCON 2005
-emon"trating ",ecia method"

)%a,, )hatty:

+e0 ??nt??(,e%0, na.e):

,e%0.na.e 1 na.e

+e0 ??*etattr??(,e%0, 9hat):

prnt ,e%0.na.e, (a,Ie+ 0or(, 9hat

ra,e 8ttrb#teDrror(9hat)

Effective Python Programming OSCON 2005
demon"tration(((

--- 8 1 )hatty(282)

--- J 1 )hatty(2J2)

--- 8 H J

8 a,Ie+ 0or ??)oer)e??

8 a,Ie+ 0or ??a++??

J a,Ie+ 0or ??)oer)e??

J a,Ie+ 0or ??ra++??

'ra)eba)I (.o,t re)ent )a%% %a,t):

>%e (F,t+n-(, %ne 1, n V

'ypeDrror: #n,#pporte+ operan+ type(,) 0or H:
2n,tan)e2 an+ 2n,tan)e2

--- prnt 8

8 a,Ie+ 0or ??,tr??

8 a,Ie+ 0or ??repr??

F??.an??.)hatty n,tan)e at 0&bG+04G))-

Effective Python Programming OSCON 2005
??*etattr?? /arning

S,ecia.ca"e ??,pe)a%?? name"

Pain, other/i"e

Python #"e" ot" of ",ecia method"

e(g( ??repr?? to ,rint



+e0 ??*etattr??(,e%0, na.e):

0 na.e.,tart,9th(2??2) an+ na.e.en+,9th(2??2):

ra,e 8ttrb#teDrror(na.e)

ret#rn ,e%0.re.ote3b5e)t.%ooI#pCa.e(na.e)
Effective Python Programming OSCON 2005
GetBSet method"

in"tead of%

prnt ,o.eob5e)t.*etPa%#e()

,o.eob5e)t.,etPa%#e(5)

#"e%

prnt ,o.eob5e)t.7a%#e

,o.eob5e)t.7a%#e 1 5
Effective Python Programming OSCON 2005
GetBSet method"

Sometime", attrib#te" need to be


com,#ted

!"e a ,ro,erty1

)%a,, Ma*):

+e0 ?*etMa*)C#.(,e%0):

ret#rn 0n+'heMa*)C#.ber()

+e0 ?,etMa*)C#.(,e%0, 7a%#e)

,et'heMa*)C#.ber(7a%#e)

.a*)C#.ber 1 property(?*etMa*)C#.,

?,etMa*)C#.)
Effective Python Programming OSCON 2005
Pro,ertie"

Pro,erty ta7e" <.5 arg#ment"%



attrb#te 1 property(*et.eth, ,et.eth, +e%.eth,

+o)122)

"et method and de method o,tiona

doc "et" a doc"tring #"e it



.onIeyCo#nt 1 property(*etMonIey,,

+o)12'he )o#nt o0 .onIey, n th, barre%2)

Ony #"e ,ro,erty /hen needed



8ttrib#te" are a ot fa"ter
Effective Python Programming OSCON 2005
-e"cri,tor"

,ro,erty ret#rn" an object caed a


de"cri,tor

e=tremey ,o/erf#, b#t yo#$ have to


read #, on them yo#r"ef

de"cri,tor" are ho/ $"ef$ get" in"erted


a" the fir"t arg#ment of a method

ca""method and "taticmethod are a"o


de"cri,tor"
Effective Python Programming OSCON 2005
"taticmethod

@ery imited #"e

Neary a/ay" better to #"e a f#nction


Effective Python Programming OSCON 2005
ca""method

8ternate con"tr#ctor"

)%a,, '.eOta.p(ob5e)t):

+e0 ??nt??(,e%0, h, ., ,):

,e%0.h, ,e%0.., ,e%0., 1 h, ., ,


W)%a,,.etho+

+e0 0ro.Otrn*()%,, ,trn*):

h,.,, 1 [nt(&) 0or & n ,trn*.,p%t(2:2)$

ret#rn )%,(h, ., ,)

8ternate con"tr#ctor" ma7e nicer 8P+

Not many other #"e"


Effective Python Programming OSCON 2005
Lca""method 1A

-ecorator"

:e,ace" thi"%

+e0 a%ternateCtor()%,, ar*#.entN,t):

...

a%ternateCtor 1 )%a,,.etho+(a%ternateCtor)

4ith thi"%

W)%a,,.etho+

+e0 a%ternateCtor()%,, ar*#.entN,t):

...
Effective Python Programming OSCON 2005
-ecorator"

-ecorator" are ,a""ed the f#nction


object, ret#rn a ne/ f#nction object

:emember to co,y f#ncEname and


EEdocEE if yo# create a ne/ f#nction
object1
Effective Python Programming OSCON 2005
)a*ine""

Python ma7e" thing" ea"y

B#t ony if yo# et it

8nytime yo# fee i7e yo#$re doing too


m#ch, ta7e a "te, bac7
Effective Python Programming OSCON 2005
S(8(S( 3heatre

dict("etdefa#t>7ey, defa#tva?

"et" a va#e >if not aready "et?, ret#rn"


va#e
Effective Python Programming OSCON 2005
"etdefa#t

3#rn" thi"%

0 Iey n +)tob5:

+)tob5[Iey$.appen+(7a%)

e%,e:

+)tob5[Iey$ 1 [7a%$

+nto thi"%

+)tob5.,et+e0a#%t(Iey, [$).appen+(7a%)

Effective Python Programming OSCON 2005
SeC#ence !n,ac7ing

Do"t thing" '#"t 4or7%



a, b, ) 1 threet#p%e

S/a, t/o va#e"%



a, b 1 b, a

Get and cear a va#e%



7a%, ,e%0.7a% 1 ,e%0.7a%, Cone
Effective Python Programming OSCON 2005
Stam,ing )icen"e Pate"

8ny time yo# find yo#r"ef /riting the


"ameB"imiar code re,eatedy, yo#$re
/or7ing too hard

!"e a tem,ate f#nction >a co"#re?


Effective Python Programming OSCON 2005
Boring re,etitive code

)%a,, MonIey:

+e0 +,p%ayCa.e8,/'MN(,e%0):

),,C%a,, 1 ,e%0.),,C%a,,

ht.%12F+7 )%a,,1S%,S-%,F4+7-2%(),,C%a,,,

,e%0.na.e)

ret#rn ht.%

+e0 +,p%ayJanana,8,/'MN(,e%0):

),,C%a,, 1 ,e%0.),,C%a,,

ht.%12F+7 )%a,,1S%,S-%,F4+7-2%(),,C%a,,,

,e%0.banana,)

ret#rn ht.%
Effective Python Programming OSCON 2005
3em,ated Don7ey

+e0 ?+,p%ayer(9hat):

+e0 te.p%ate(,e%0):

7a% 1 *etattr(,e%0, 9hat)

),,C%a,, 1 ,e%0.),,C%a,,

ret#rn 2F+7 )%a,,1S%,S-%,F4+7-2%(),,C%a,,,

7a%)

ret#rn ht.%

ret#rn te.p%ate


)%a,, MonIey:

+,p%ayCa.e8,/'MN 1 ?+,p%ayer(2na.e2)

+,p%ayJanana,8,/'MN 1 ?+,p%ayer(2banana,2)
Effective Python Programming OSCON 2005
Da7ing 3em,ate" "aner

+e0 ?+,p%ayer(9hat):

+e0 te.p%ate(,e%0, 9hat19hat):

...

template.func_name = 'display%sAsHtml'%(

what.capitalize())

template.__doc__ = 'Returns %s as HT!'%what

ret#rn te.p%ate
Effective Python Programming OSCON 2005
!niver"a Ne/ine Dode

4indo/", Dac, !ni= have different ine


ending"

8nnoying

O,en fie" /ith $r!$, and it j#"t /or7"



0p 1 open(2,o.e0%e.t&t2, 2rB2)

Effective Python Programming OSCON 2005
codec"(o,en

codec"(o,en ,rovide" a fie.i7e object


in a ,artic#ar encoding

#"ef# for reading and /riting

more d#c7 ty,ing


Effective Python Programming OSCON 2005
Pan for !nicode

D#ch ea"ier if yo# "tart o#t ao/ing


#nicode

Even if not, it$" not too hard to retrofit


Effective Python Programming OSCON 2005
ba"e"tring

Parent ca"" for "tr and #nicode

!"ef# in i"in"tance>? chec7"



--- ,n,tan)e(2.oo,e2, ba,e,trn*)

'r#e

--- ,n,tan)e(#2.XX,e2, ba,e,trn*)

'r#e

Effective Python Programming OSCON 2005
3he +n"tant G#ide to i<Mn

i<Mn yo#r "tring"%



0ro. *ette&t .port *ette&t a, ?

?(2Dnter yo#r na.e2)

-ecode "tring" on in,#t%



byte, 1 (naY7e(

#n,tr 1 byte,.+e)o+e(2,o""5Z!12)

Encode #nicode on o#t,#t%



prnt #n,tr.en)o+e(2,o""5Z!12, 2rep%a)e2)
Effective Python Programming OSCON 2005
Batterie" +nc#ded

Python "hi," /ith a arge "td ibrary

-on$t re.invent the /hee


Effective Python Programming OSCON 2005
4hen 3hing" Go Pear.Sha,ed

-eb#gging

3e"ting
Effective Python Programming OSCON 2005
S(8(S( 3heatre

3he "inge mo"t #"ef# Python tric7 +


7no/%

.port p+b[ p+b.,et?tra)e()

4hen e=ec#ted, dro," into the Python


deb#gger
Effective Python Programming OSCON 2005
#nitte"t

Python "tandard #nitte"t mod#e

Port of '#nit

Da7e" /riting te"t" not.too.horribe

8P+ i" "ti a bit c#mber"ome


Effective Python Programming OSCON 2005
docte"t

Dore Pythonic

Perfect for the a*y ,rogrammer

C#t.n.,a"te from an interactive "e""ion

-o#be" a" doc#mentation and


e=am,e"
Effective Python Programming OSCON 2005
:#nning 3e"t"

8 good te"t r#nner ma7e" it more i7ey


,eo,e /i act#ay r#n the te"t"

te"t(,y >in No,eI?


Effective Python Programming OSCON 2005
-eaing /ith tracebac7"

Sometime", the defa#t tracebac7 i"n$t


/hat yo# /ant

tra)eba)I mod#e

try:

....

e&)ept:

e, 7, tb 1 ,y,.e&)?n0o()

tra)eba)I.prnt?tb(t)
Effective Python Programming OSCON 2005
cgitb

-eb#gging CG+ "cri,t" can be horribe



.port )*tb[ )*tb.enab%e()

-i",ay" nicey formatted tracebac7"



conte=t

variabe"

arg#ment"

Can og in te=t or htm, to the bro/"er


or fie"
Effective Python Programming OSCON 2005
Da7ing )ife 0ard 6or Ho#r"ef

3hing" to avoid

:ecogni"ing refactoring target"

)earning from >bad? e=am,e"


Effective Python Programming OSCON 2005
S(8(S( 3heatre

Bare e=ce,t% ca#"e" /i neary a/ay"


bite yo# ater

Sienty eating e=ce,tion" i" bad

e=ce,t% "ho#d either og the e=ce,tion,


or re.rai"e it

'#"t $rai"e$ /i re.rai"e the c#rrent


e=ce,tion
Effective Python Programming OSCON 2005
Con"i"tent Coding Stye

Pic7 a "tye, and "tic7 to it



PEP 00M ha" one, or choo"e yo#r o/n

!"e too" /here nece""ary



emac" ,ython mode

reindent(,y

Pic7 a con"i"tent indent "tye1


Effective Python Programming OSCON 2005
from mod#e im,ort J

-on$t

6ig#ring o#t /here a name come" from


"ho#d not be ,ainf#
Effective Python Programming OSCON 2005
Circ#ar +m,ort"

Circ#ar im,ort" ead to "#bte b#g"%

Dod#e 8%

.port .o+#%eJ

Dod#e B%

.port .o+#%e8

-efer im,ort" #nti yo# need them to


fi= thi"
Effective Python Programming OSCON 2005
more on e=ce,tion"

:ai"ing a ne/ e=ce,tion from an


e=ce,t% ca#"e often ma7e" deb#gging
harder

3he ne/ tracebac7 /i ,oint at the


e=ce,t% boc7, not the origina
e=ce,tion

8 bare $rai"e$ /i re.rai"e the c#rrent


e=ce,tion
Effective Python Programming OSCON 2005
:efactoring 3arget"

)earn to ",ot ,otentia ,robem"


Effective Python Programming OSCON 2005
)ong 8rg#ment )i"t"

Once a f#nction get" ,a"t a co#,e of


arg#ment", either%

refactor it

or #"e 7ey/ord arg#ment"

+e0 ,o.e/+eo#,>#n)ton(0r,tna.e, ,#rna.e, a++r1,

a++r2, zp)o+e, )ty, ,tate):

....


,o.e/+eo#,>#n)ton(0r,tna.e1S8nthonyS,

,#rna.e1SJa&terS, ....
Effective Python Programming OSCON 2005
6ormat String"

Simiar ,robem /ith format "tring"


#"ing O o,erator

!"e the dict form%



a++r<n0o 1 +)t(0r,tna.e128nthony2,

,#rna.e12Ja&ter2, ...)

%abe% 1 TSS%(0r,tna.e), %(,#rna.e),

%(a++r1),

%(a++r2),

%()ty),, %(,tate),

%(zp)o+e),SSS % a++r<n0o
Effective Python Programming OSCON 2005
"tring(3em,ate

Even "im,er

--- 0ro. ,trn* .port 'e.p%ate

--- , 1 'e.p%ate(2\)hee,e , 0ro. \@)o#ntryA2)

--- prnt ,.,#b,tt#te()hee,e12Go#+a2, )o#ntry12the
Cether%an+,2)

Go#+a , 0ro. the Cether%an+,

--- prnt ,.,#b,tt#te()hee,e12Go#+a2)

'ra)eba)I (.o,t re)ent )a%% %a,t):

[...$

ReyDrror: 2)o#ntry2

--- prnt ,.,a0e?,#b,tt#te()hee,e12Go#+a2)

Go#+a , 0ro. \@)o#ntryA

Effective Python Programming OSCON 2005
P 22 Per1A1

3he P "ign i" only acce,ted in the


"tring" ,a""ed to "tring(3em,ate

)ot" of other ang#age" #"e P . it$" the


obvio#" choice
Effective Python Programming OSCON 2005
7ey in "eC#ence

8ny time yo# #"e $in$, chec7 the :0S

+f a "eC#ence, ho/ big /i it getA

O>N?

!"e a dict, or a "et


Effective Python Programming OSCON 2005
3oo many goba"

Over#"e of $*%oba%$ #"#ay indicate"


,oor code

:efactor into a ca"", "toring the goba


va#e" a" attrib#te"
Effective Python Programming OSCON 2005
)earning by >bad? e=am,e

)ot" of Python code to earn from

Some of it i" od

Peo,e ,ic7 #, bad habit" from thi"


Effective Python Programming OSCON 2005
ma,BfiterBred#ce

ma, and fiter #"ing a ambda "ho#d


be re,aced /ith i"tcom," or gene=,r"

red#ce% j#"t don$t #"e



"#m>? re,aced Q0O of #"e ca"e"

other #"e ca"e" #"#ay ead" to
head"cratching
Effective Python Programming OSCON 2005
"tring mod#e

"tring method" are better



--- .port ,trn*

--- na.e 1 2anthony2

--- prnt ,trn*.#pper(na.e)

8C'/3C]

--- prnt na.e.#pper()

8C'/3C]

:emember% "tring" are imm#tabe,


method" ret#rn a co,y
Effective Python Programming OSCON 2005
bac7"a"h ine contin#ation"

8mo"t never needed

Not needed if there$" o,en brace"

So /ra, in > ?

4or7" for im,ort, too1 >in 2(5?




0ro. pa)Ia*e.,#bpI*..o+#%e .port (8na.e, Jna.e,

Cna.e, Dna.e)
Effective Python Programming OSCON 2005
ha"E7ey>?

7ey in dict

dict(get>7ey, defa#t?
Effective Python Programming OSCON 2005
Circ#ar reference"

Not "o m#ch of a ,robem no/


>garbage coector?

:emember% ??+e%?? "to," GC1


Effective Python Programming OSCON 2005
:eg#ar E=,re""ion"

Sho#d not be the fir"t hammer in yo#r


toobo=

Sometime", a rea ,ar"er i" better

+f yo# m#"t #"e them(((


Effective Python Programming OSCON 2005
re(com,ie>?

re(com,ie>? ret#rn" a com,ied


e=,re""ion

m#ch, m#ch fa"ter than re.com,iing


each time

nicer 8P+, too


Effective Python Programming OSCON 2005
named :E gro#,"

!"e named :E gro#," rather than


n#mbered one"

r 1 re.)o.p%e(2(VPFna.e-[^ $H) (VPF,#rna.e-[^ $H)2)

.at)h 1 r..at)h(28nthony Ja&ter2)

.at)h.*ro#p(2,#rna.e2)
Effective Python Programming OSCON 2005
-efen"ive :E ,rogramming

Chec7 the "tring matche" /hat yo#


e=,ect, fir"t

-eb#gging com,e= :E fai#re" i" a


/ord of h#rt
Effective Python Programming OSCON 2005
Efficient Python Programming

Da7ing Python Go 6a"t


Effective Python Programming OSCON 2005
S(8(S( 3heatre

f#nction ca" are "o/


Effective Python Programming OSCON 2005
Da7ing yo#r Python code fa"t

dict", i"t("ort>? are highy t#ned

goba" are "o/er than oca"

i"t(,o,>0?, i"t(in"ert>0, va#e? are "o/



rever"e yo#r i"t, or #"e coection"(deC#e

move fi=ed code o#t of the critica ,ath


Effective Python Programming OSCON 2005
,rofieBhot"hot

6ig#re o#t /here the "o/ bit" are

Get the code right fir"t >/ith #nit te"t"1?


and then o,timi"e
Effective Python Programming OSCON 2005
n#mericBn#marray

+n"aney o,timi"ed array o,eration"

+f deaing /ith n#mber", #"e them


Effective Python Programming OSCON 2005
Pyre=

Python diaect that$" com,ied to C

Start /ith "traight Python code, add


decaration" to #"e C ty,e"

Ony o,timi"e the hot ",ot"

D#ch ea"ier than trying to /rite


"traight C code e=ten"ion"
Effective Python Programming OSCON 2005
??,%ot,??

O,timi"ation tric7

Python object" "tore attrib#te" in a


dictionary

??,%ot,?? i" a fi=ed i"t

red#ce" memory con"#m,tion /hen


yo# have many "ma object"
Effective Python Programming OSCON 2005
??,%ot,??

-on$t #"e ??,%ot,?? a" "ome "ort of


ty,e.chec7ing hac7

??,%ot,?? and "#bca""ing 22 h#rt


Effective Python Programming OSCON 2005
3ying it a bac7 together

'ava -OD Node

Good e=am,e of a bad Python 8P+


Effective Python Programming OSCON 2005
Node(getChidNode">?

:et#rn" the chid node" of the c#rrent


Node(

Either%

Node(chidNode"

or

Da7e Node an iterator that iterate"
thro#gh it$" chidren
Effective Python Programming OSCON 2005
get@a#e>?B"et@a#e>?

+n"tead, j#"t #"e node(va#e

Or #"e a ,ro,erty if va#e i" com,#ted,


or need" to be chec7ed /hen "et
Effective Python Programming OSCON 2005
i"SameNode>?

+m,ement a ??eE?? method



th,Co+e 11 otherCo+e

Note that $i"$ might not be right



if yo# can have t/o Node in"tance"
,ointing at the "ame ,art of the -OD
Effective Python Programming OSCON 2005
com,are-oc#mentPo"ition>?

Com,are" Node$" doc#ment ,o"ition to


another Node(

+n"tead, im,ement a (,o"ition attrib#te


that can be com,ared%

th,Co+e.po,ton F otherCo+e.po,ton

Or even Node(EEtEE, Node(EEgtEE



Co#d be a bit too ceverBmagic
Effective Python Programming OSCON 2005
,arentBchid reference cyce

:emember, a ,arent chid reference


cyce i"n$t a ,robem

>So ong a" Node doe"n$t im,ement a
??+e%?? method1?

Sti, don$t create them #nnece""ariy



:eference" 7ee, object" aive
Effective Python Programming OSCON 2005
4ra,,ing !,

4rite Python code in Python

Dight invove #n.earning "ome habit"


from other ang#age"

Dore information in the note" for the"e


"ide"(((
Effective Python Programming OSCON 2005

Bea#tif# i" better than #gy(

E=,icit i" better than im,icit(

Sim,e i" better than com,e=(

Com,e= i" better than com,icated(

6at i" better than ne"ted(

S,ar"e i" better than den"e(

:eadabiity co#nt"(

S,ecia ca"e" aren$t ",ecia eno#gh to brea7 the r#e"(

8tho#gh ,racticaity beat" ,#rity(

Error" "ho#d never ,a"" "ienty(

!ne"" e=,icity "ienced(

+n the face of ambig#ity, ref#"e the tem,tation to g#e""(

3here "ho#d be one and ,referaby ony one obvio#" /ay to do it(

8tho#gh that /ay may not be obvio#" at fir"t #ne"" yo#$re -#tch(

No/ i" better than never(

8tho#gh never i" often better than JrightJ no/(

+f the im,ementation i" hard to e=,ain, it$" a bad idea(

+f the im,ementation i" ea"y to e=,ain, it may be a good idea(

Name",ace" are one hon7ing great idea .. et$" do more of tho"e1

S-ar putea să vă placă și