google的python编码规范.docx
《google的python编码规范.docx》由会员分享,可在线阅读,更多相关《google的python编码规范.docx(32页珍藏版)》请在冰豆网上搜索。
google的python编码规范
GooglePythonStyleGuide
Revision2.19
AmitPatel
AntoinePicard
EugeneJhong
JeremyHylton
MattSmart
MikeShields
Eachstylepointhasasummaryforwhichadditionalinformationisavailablebytogglingtheaccompanyingarrowbuttonthatlooksthisway:
▶.Youmaytoggleallsummarieswiththebigarrowbutton:
▶ Toggleallsummaries
TableofContents
PythonLanguageRules
pychecker Imports Packages Exceptions Globalvariables Nested/Local/InnerClassesandFunctionsListComprehensions DefaultIteratorsandOperators Generators LambdaFunctionsDefaultArgumentValues Properties True/Falseevaluations DeprecatedLanguageFeaturesLexicalScoping FunctionandMethodDecorators Threading PowerFeatures
PythonStyleRules
Semicolons Linelength Parentheses Indentation BlankLines Whitespace PythonInterpreterComments Classes Strings TODOComments Importsformatting Statements AccessControl NamingMain
ImportantNote
DisplayingHiddenDetailsinthisGuide
link▽
Thisstyleguidecontainsmanydetailsthatareinitiallyhiddenfromview.Theyaremarkedbythetriangleicon,whichyouseehereonyourleft.Clickitnow.Youshouldsee"Hooray"appearbelow.
Hooray!
Nowyouknowyoucanexpandpointstogetmoredetails.Alternatively,there'sa"toggleall"atthetopofthisdocument.
Background
PythonisthemainscriptinglanguageusedatGoogle.Thisstyleguideisalistof dosand don'tsforPythonprograms.
Tohelpyouformatcodecorrectly,we'vecreateda settingsfileforVim.ForEmacs,thedefaultsettingsshouldbefine.
PythonLanguageRules
pychecker
link▽
Run pychecker overyourcode.
Definition:
PyCheckerisatoolforfindingbugsinPythonsourcecode.ItfindsproblemsthataretypicallycaughtbyacompilerforlessdynamiclanguageslikeCandC++.Itissimilartolint.BecauseofthedynamicnatureofPython,somewarningsmaybeincorrect;however,spuriouswarningsshouldbefairlyinfrequent.
Pros:
Catcheseasy-to-misserrorsliketypos,use-vars-before-assignment,etc.
Cons:
pychecker isn'tperfect.Totakeadvantageofit,we'llneedtosometimes:
a)Writearounditb)Suppressitswarningsc)Improveitord)Ignoreit.
Decision:
Makesureyourun pychecker onyourcode.
Forinformationonhowtorun pychecker,seethe pycheckerhomepage
Tosuppresswarnings,youcansetamodule-levelvariablenamed __pychecker__ tosuppressappropriatewarnings.Forexample:
__pychecker__='no-callinitno-classattr'
Suppressinginthiswayhastheadvantagethatwecaneasilysearchforsuppressionsandrevisitthem.
Youcangetalistofpycheckerwarningsbydoing pychecker--help.
Unusedargumentwarningscanbesuppressedbyusing`_'astheidentifierfortheunusedargumentorprefixingtheargumentnamewith`unused_'.Insituationswherechangingtheargumentnamesisinfeasible,youcanmentionthematthebeginningofthefunction.Forexample:
deffoo(a,unused_b,unused_c,d=None,e=None):
(d,e)=(d,e)#Silencepychecker
returna
Ideally,pycheckerwouldbeextendedtoensurethatsuch`unuseddeclarations'weretrue.
Imports
link▽
Use importsforpackagesandmodulesonly.
Definition:
Reusabilitymechanismforsharingcodefromonemoduletoanother.
Pros:
Thenamespacemanagementconventionissimple.Thesourceofeachidentifierisindicatedinaconsistentway; x.Obj saysthatobject Obj isdefinedinmodule x.
Cons:
Modulenamescanstillcollide.Somemodulenamesareinconvenientlylong.
Decision:
Use importx forimportingpackagesandmodules.
Use fromximporty where x isthepackageprefixand y isthemodulenamewithnoprefix.
Use fromximportyasz iftwomodulesnamed z aretobeimportedorif y isaninconvenientlylongname.
Forexamplethemodule sound.effects.echo maybeimportedasfollows:
fromsound.effectsimportecho
...
echo.EchoFilter(input,output,delay=0.7,atten=4)
Donotuserelativenamesinimports.Evenifthemoduleisinthesamepackage,usethefullpackagename.Thishelpspreventunintentionallyimportingapackagetwice.
Packages
link▽
Importeachmoduleusingthefullpathnamelocationofthemodule.
Pros:
Avoidsconflictsinmodulenames.Makesiteasiertofindmodules.
Cons:
Makesithardertodeploycodebecauseyouhavetoreplicatethepackagehierarchy.
Decision:
Allnewcodeshouldimporteachmodulebyitsfullpackagename.
Importsshouldbeasfollows:
#Referenceincodewithcompletename.
importsound.effects.echo
#Referenceincodewithjustmodulename(preferred).
fromsound.effectsimportecho
Exceptions
link▽
Exceptionsareallowedbutmustbeusedcarefully.
Definition:
Exceptionsareameansofbreakingoutofthenormalflowofcontrolofacodeblocktohandleerrorsorotherexceptionalconditions.
Pros:
Thecontrolflowofnormaloperationcodeisnotclutteredbyerror-handlingcode.Italsoallowsthecontrolflowtoskipmultipleframeswhenacertainconditionoccurs,e.g.,returningfromNnestedfunctionsinonestepinsteadofhavingtocarry-througherrorcodes.
Cons:
Maycausethecontrolflowtobeconfusing.Easytomisserrorcaseswhenmakinglibrarycalls.
Decision:
Exceptionsmustfollowcertainconditions:
∙Raiseexceptionslikethis:
raiseMyException("Errormessage") or raiseMyException.Donotusethetwo-argumentform(raiseMyException,"Errormessage")ordeprecatedstring-basedexceptions(raise"Errormessage").
∙Modulesorpackagesshoulddefinetheirowndomain-specificbaseexceptionclass,whichshouldinheritfromthebuilt-inExceptionclass.Thebaseexceptionforamoduleshouldbecalled Error.
∙classError(Exception):
pass
∙Neverusecatch-all except:
statements,orcatch Exception or StandardError,unlessyouarere-raisingtheexceptionorintheoutermostblockinyourthread(andprintinganerrormessage).Pythonisverytolerantinthisregardandexcept:
willreallycatcheverythingincludingPythonsyntaxerrors.Itiseasytohiderealbugsusing except:
.
∙Minimizetheamountofcodeina try/except block.Thelargerthebodyofthe try,themorelikelythatanexceptionwillberaisedbyalineofcodethatyoudidn'texpecttoraiseanexception.Inthosecases,the try/except blockhidesarealerror.
∙Usethe finally clausetoexecutecodewhetherornotanexceptionisraisedinthe try block.Thisisoftenusefulforcleanup,i.e.,closingafile.
Globalvariables
link▽
Avoidglobalvariables.
Definition:
Variablesthataredeclaredatthemodulelevel.
Pros:
Occasionallyuseful.
Cons:
Hasthepotentialtochangemodulebehaviorduringtheimport,becauseassignmentstomodule-levelvariablesaredonewhenthemoduleisimported.
Decision:
Avoidglobalvariablesinfavorofclassvariables.Someexceptionsare:
∙Defaultoptionsforscripts.
∙Module-levelconstants.Forexample:
PI=3.14159.Constantsshouldbenamedusingallcapswithunderscores;seeNaming below.
∙Itissometimesusefulforglobalstocachevaluesneededorreturnedbyfunctions.
∙Ifneeded,globalsshouldbemadeinternaltothemoduleandaccessedthroughpublicmodulelevelfunctions;see Namingbelow.
Nested/Local/InnerClassesandFunctions
link▽
Nested/local/innerclassesandfunctionsarefine.
Definition:
Aclasscanbedefinedinsideofamethod,function,orclass.Afunctioncanbedefinedinsideamethodorfunction.Nestedfunctionshaveread-onlyaccesstovariablesdefinedinenclosingscopes.
Pros:
Allowsdefinitionofutilityclassesandfunctionsthatareonlyusedinsideofaverylimitedscope.Very ADT-y.
Cons:
Instancesofnestedorlocalclassescannotbepickled.
Decision:
Theyarefine.
ListComprehensions
link▽
Okaytouseforsimplecases.
Definition:
Listcomprehensionsandgeneratorexpressionsprovideaconciseandefficientwaytocreatelistsanditeratorswithoutresortingtotheuseof map(), filter(),or lambda.
Pros:
Simplelistcomprehensionscanbeclearerandsimplerthanotherlistcreationtechniques.Generatorexpressionscanbeveryefficient,sincetheyavoidthecreationofalistentirely.
Cons:
Complicatedlistcomprehensionsorgeneratorexpressionscanbehardtoread.
Decision:
Okaytouseforsimplecases.Eachportionmustfitononeline:
mappingexpression, for clause,filterexpression.Multiplefor clausesorfilterexpressionsarenotpermitted.Useloopsinsteadwhenthingsgetmorecomplicated.
No:
result=[(x,y)forxinrange(10)foryinrange(5)ifx*y>10]
return((x,y,z)
forxinxrange(5)
foryinxrange(5)
ifx!
=y
forzinxrange(5)
ify!
=z)
Yes:
result=[]
forxinrange(10):
foryinrange(5):
ifx*y>10:
result.append((x,y))
forxinxrange(5):
foryinxrange(5):
ifx!
=y:
forzinxrange(5):
ify!
=z:
yield(x,y,z)
return((x,complicated_transform(x))
forxinlong_generator_function(parameter)
ifxisnotNone)
squares=[x*xforxinrange(10)]
eat(jelly_beanforjelly_beaninjelly_beans
ifjelly_bean.color=='black')
DefaultIteratorsandOperators
link▽
Usedefaultiteratorsandoperatorsfortypesthatsupportthem,likelists,dictionaries,andfiles.
Definition:
Containertypes,likedictionariesandlists,definedefaultiteratorsandmembershiptestoperators("in"and"notin").
Pros:
Thedefaultiteratorsandoperatorsaresimpleandefficient.Theyexpresstheoperationdirectly,withoutextramethodcalls.Afunctionthatusesdefaultoperatorsisgeneric.Itcanbeusedwithanytypethatsupportstheoperation.
Cons:
Youcan'ttellthetypeofobjectsbyreadingthemethodnames(e.g.has_key()meansadictionary).Thisisalsoanadvantage.
Decision:
Usedefaultiteratorsandoperatorsfortypesthatsupportthem,likelists,dictionaries,andfiles.Thebuilt-intypesdefineiteratormethods,too.Preferthesemethod