google的python编码规范Word文件下载.docx
《google的python编码规范Word文件下载.docx》由会员分享,可在线阅读,更多相关《google的python编码规范Word文件下载.docx(32页珍藏版)》请在冰豆网上搜索。
![google的python编码规范Word文件下载.docx](https://file1.bdocx.com/fileroot1/2023-2/3/99d4fbd8-fc71-4fd0-a4a1-8f75f9cdbc68/99d4fbd8-fc71-4fd0-a4a1-8f75f9cdbc681.gif)
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.
pychecker
Run
overyourcode.
Definition:
PyCheckerisatoolforfindingbugsinPythonsourcecode.ItfindsproblemsthataretypicallycaughtbyacompilerforlessdynamiclanguageslikeCandC++.Itissimilartolint.BecauseofthedynamicnatureofPython,somewarningsmaybeincorrect;
however,spuriouswarningsshouldbefairlyinfrequent.
Pros:
Catcheseasy-to-misserrorsliketypos,use-vars-before-assignment,etc.
Cons:
isn'
tperfect.Totakeadvantageofit,we'
llneedtosometimes:
a)Writearounditb)Suppressitswarningsc)Improveitord)Ignoreit.
Decision:
Makesureyourun
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
Use
importsforpackagesandmodulesonly.
Reusabilitymechanismforsharingcodefromonemoduletoanother.
Thenamespacemanagementconventionissimple.Thesourceofeachidentifierisindicatedinaconsistentway;
x.Obj
saysthatobject
Obj
isdefinedinmodule
x.
Modulenamescanstillcollide.Somemodulenamesareinconvenientlylong.
importx
forimportingpackagesandmodules.
fromximporty
where
x
isthepackageprefixand
y
isthemodulenamewithnoprefix.
fromximportyasz
iftwomodulesnamed
z
aretobeimportedorif
isaninconvenientlylongname.
Forexamplethemodule
sound.effects.echo
maybeimportedasfollows:
fromsound.effectsimportecho
...
echo.EchoFilter(input,output,delay=0.7,atten=4)
Donotuserelativenamesinimports.Evenifthemoduleisinthesamepackage,usethefullpackagename.Thishelpspreventunintentionallyimportingapackagetwice.
Packages
Importeachmoduleusingthefullpathnamelocationofthemodule.
Avoidsconflictsinmodulenames.Makesiteasiertofindmodules.
Makesithardertodeploycodebecauseyouhavetoreplicatethepackagehierarchy.
Allnewcodeshouldimporteachmodulebyitsfullpackagename.
Importsshouldbeasfollows:
#Referenceincodewithcompletename.
importsound.effects.echo
#Referenceincodewithjustmodulename(preferred).
Exceptions
Exceptionsareallowedbutmustbeusedcarefully.
Exceptionsareameansofbreakingoutofthenormalflowofcontrolofacodeblocktohandleerrorsorotherexceptionalconditions.
Thecontrolflowofnormaloperationcodeisnotclutteredbyerror-handlingcode.Italsoallowsthecontrolflowtoskipmultipleframeswhenacertainconditionoccurs,e.g.,returningfromNnestedfunctionsinonestepinsteadofhavingtocarry-througherrorcodes.
Maycausethecontrolflowtobeconfusing.Easytomisserrorcaseswhenmakinglibrarycalls.
Exceptionsmustfollowcertainconditions:
∙Raiseexceptionslikethis:
raiseMyException("
Errormessage"
)
or
raiseMyException.Donotusethetwo-argumentform(raiseMyException,"
)ordeprecatedstring-basedexceptions(raise"
).
∙Modulesorpackagesshoulddefinetheirowndomain-specificbaseexceptionclass,whichshouldinheritfromthebuilt-inExceptionclass.Thebaseexceptionforamoduleshouldbecalled
Error.
∙classError(Exception):
pass
∙Neverusecatch-all
except:
statements,orcatch
Exception
StandardError,unlessyouarere-raisingtheexceptionorintheoutermostblockinyourthread(andprintinganerrormessage).Pythonisverytolerantinthisregardandexcept:
willreallycatcheverythingincludingPythonsyntaxerrors.Itiseasytohiderealbugsusing
.
∙Minimizetheamountofcodeina
try/except
block.Thelargerthebodyofthe
try,themorelikelythatanexceptionwillberaisedbyalineofcodethatyoudidn'
texpecttoraiseanexception.Inthosecases,the
blockhidesarealerror.
∙Usethe
finally
clausetoexecutecodewhetherornotanexceptionisraisedinthe
try
block.Thisisoftenusefulforcleanup,i.e.,closingafile.
Globalvariables
Avoidglobalvariables.
Variablesthataredeclaredatthemodulelevel.
Occasionallyuseful.
Hasthepotentialtochangemodulebehaviorduringtheimport,becauseassignmentstomodule-levelvariablesaredonewhenthemoduleisimported.
Avoidglobalvariablesinfavorofclassvariables.Someexceptionsare:
∙Defaultoptionsforscripts.
∙Module-levelconstants.Forexample:
PI=3.14159.Constantsshouldbenamedusingallcapswithunderscores;
seeNaming
below.
∙Itissometimesusefulforglobalstocachevaluesneededorreturnedbyfunctions.
∙Ifneeded,globalsshouldbemadeinternaltothemoduleandaccessedthroughpublicmodulelevelfunctions;
see
Namingbelow.
Nested/Local/InnerClassesandFunctions
Nested/local/innerclassesandfunctionsarefine.
Aclasscanbedefinedinsideofamethod,function,orclass.Afunctioncanbedefinedinsideamethodorfunction.Nestedfunctionshaveread-onlyaccesstovariablesdefinedinenclosingscopes.
Allowsdefinitionofutilityclassesandfunctionsthatareonlyusedinsideofaverylimitedscope.Very
ADT-y.
Instancesofnestedorlocalclassescannotbepickled.
Theyarefine.
ListComprehensions
Okaytouseforsimplecases.
Listcomprehensionsandgeneratorexpressionsprovideaconciseandefficientwaytocreatelistsanditeratorswithoutresortingtotheuseof
map(),
filter(),or
lambda.
Simplelistcomprehensionscanbeclearerandsimplerthanotherlistcreationtechniques.Generatorexpressionscanbeveryefficient,sincetheyavoidthecreationofalistentirely.
Complicatedlistcomprehensionsorgeneratorexpressionscanbehardtoread.
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):
=y:
forzinxrange(5):
=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
Usedefaultiteratorsandoperatorsfortypesthatsupportthem,likelists,dictionaries,andfiles.
Containertypes,likedictionariesandlists,definedefaultiteratorsandmembershiptestoperators("
in"
and"
notin"
Thedefaultiteratorsandoperatorsaresimpleandefficient.Theyexpresstheoperationdirectly,withoutextramethodcalls.Afunctionthatusesdefaultoperatorsisgeneric.Itcanbeusedwithanytypethatsupportstheoperation.
Youcan'
ttellthetypeofobjectsbyreadingthemethodnames(e.g.has_key()meansadictionary).Thisisalsoanadvantage.
Usedefaultiteratorsandoperatorsfortypesthatsupportthem,likelists,dictionaries,andfiles.Thebuilt-intypesdefineiteratormethods,too.Preferthesemethod