google的python编码规范Word文件下载.docx

上传人:b****7 文档编号:22357864 上传时间:2023-02-03 格式:DOCX 页数:32 大小:31.87KB
下载 相关 举报
google的python编码规范Word文件下载.docx_第1页
第1页 / 共32页
google的python编码规范Word文件下载.docx_第2页
第2页 / 共32页
google的python编码规范Word文件下载.docx_第3页
第3页 / 共32页
google的python编码规范Word文件下载.docx_第4页
第4页 / 共32页
google的python编码规范Word文件下载.docx_第5页
第5页 / 共32页
点击查看更多>>
下载资源
资源描述

google的python编码规范Word文件下载.docx

《google的python编码规范Word文件下载.docx》由会员分享,可在线阅读,更多相关《google的python编码规范Word文件下载.docx(32页珍藏版)》请在冰豆网上搜索。

google的python编码规范Word文件下载.docx

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 

isthepackageprefixand 

isthemodulenamewithnoprefix. 

fromximportyasz 

iftwomodulesnamed 

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工作范文 > 行政公文

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1