google的python编码规范Word文件下载.docx
- 文档编号:22357864
- 上传时间:2023-02-03
- 格式:DOCX
- 页数:32
- 大小:31.87KB
google的python编码规范Word文件下载.docx
《google的python编码规范Word文件下载.docx》由会员分享,可在线阅读,更多相关《google的python编码规范Word文件下载.docx(32页珍藏版)》请在冰豆网上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- google python 编码 规范
![提示](https://static.bdocx.com/images/bang_tan.gif)