ast — Abstract Syntax Trees — Python 3.10.4 documentation

文章推薦指數: 80 %
投票人數:10人

The ast module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python ... Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» PythonLanguageServices» ast—AbstractSyntaxTrees | ast—AbstractSyntaxTrees¶ Sourcecode:Lib/ast.py TheastmodulehelpsPythonapplicationstoprocesstreesofthePython abstractsyntaxgrammar.Theabstractsyntaxitselfmightchangewitheach Pythonrelease;thismodulehelpstofindoutprogrammaticallywhatthecurrent grammarlookslike. Anabstractsyntaxtreecanbegeneratedbypassingast.PyCF_ONLY_ASTas aflagtothecompile()built-infunction,orusingtheparse() helperprovidedinthismodule.Theresultwillbeatreeofobjectswhose classesallinheritfromast.AST.Anabstractsyntaxtreecanbe compiledintoaPythoncodeobjectusingthebuilt-incompile()function. AbstractGrammar¶ Theabstractgrammariscurrentlydefinedasfollows: --ASDL's4builtintypesare: --identifier,int,string,constant modulePython { mod=Module(stmt*body,type_ignore*type_ignores) |Interactive(stmt*body) |Expression(exprbody) |FunctionType(expr*argtypes,exprreturns) stmt=FunctionDef(identifiername,argumentsargs, stmt*body,expr*decorator_list,expr?returns, string?type_comment) |AsyncFunctionDef(identifiername,argumentsargs, stmt*body,expr*decorator_list,expr?returns, string?type_comment) |ClassDef(identifiername, expr*bases, keyword*keywords, stmt*body, expr*decorator_list) |Return(expr?value) |Delete(expr*targets) |Assign(expr*targets,exprvalue,string?type_comment) |AugAssign(exprtarget,operatorop,exprvalue) --'simple'indicatesthatweannotatesimplenamewithoutparens |AnnAssign(exprtarget,exprannotation,expr?value,intsimple) --use'orelse'becauseelseisakeywordintargetlanguages |For(exprtarget,expriter,stmt*body,stmt*orelse,string?type_comment) |AsyncFor(exprtarget,expriter,stmt*body,stmt*orelse,string?type_comment) |While(exprtest,stmt*body,stmt*orelse) |If(exprtest,stmt*body,stmt*orelse) |With(withitem*items,stmt*body,string?type_comment) |AsyncWith(withitem*items,stmt*body,string?type_comment) |Match(exprsubject,match_case*cases) |Raise(expr?exc,expr?cause) |Try(stmt*body,excepthandler*handlers,stmt*orelse,stmt*finalbody) |Assert(exprtest,expr?msg) |Import(alias*names) |ImportFrom(identifier?module,alias*names,int?level) |Global(identifier*names) |Nonlocal(identifier*names) |Expr(exprvalue) |Pass|Break|Continue --col_offsetisthebyteoffsetintheutf8stringtheparseruses attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) --BoolOp()canuseleft&right? expr=BoolOp(boolopop,expr*values) |NamedExpr(exprtarget,exprvalue) |BinOp(exprleft,operatorop,exprright) |UnaryOp(unaryopop,exproperand) |Lambda(argumentsargs,exprbody) |IfExp(exprtest,exprbody,exprorelse) |Dict(expr*keys,expr*values) |Set(expr*elts) |ListComp(exprelt,comprehension*generators) |SetComp(exprelt,comprehension*generators) |DictComp(exprkey,exprvalue,comprehension*generators) |GeneratorExp(exprelt,comprehension*generators) --thegrammarconstrainswhereyieldexpressionscanoccur |Await(exprvalue) |Yield(expr?value) |YieldFrom(exprvalue) --needsequencesforcomparetodistinguishbetween --x<4<3and(x<4)<3 |Compare(exprleft,cmpop*ops,expr*comparators) |Call(exprfunc,expr*args,keyword*keywords) |FormattedValue(exprvalue,intconversion,expr?format_spec) |JoinedStr(expr*values) |Constant(constantvalue,string?kind) --thefollowingexpressioncanappearinassignmentcontext |Attribute(exprvalue,identifierattr,expr_contextctx) |Subscript(exprvalue,exprslice,expr_contextctx) |Starred(exprvalue,expr_contextctx) |Name(identifierid,expr_contextctx) |List(expr*elts,expr_contextctx) |Tuple(expr*elts,expr_contextctx) --canappearonlyinSubscript |Slice(expr?lower,expr?upper,expr?step) --col_offsetisthebyteoffsetintheutf8stringtheparseruses attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) expr_context=Load|Store|Del boolop=And|Or operator=Add|Sub|Mult|MatMult|Div|Mod|Pow|LShift |RShift|BitOr|BitXor|BitAnd|FloorDiv unaryop=Invert|Not|UAdd|USub cmpop=Eq|NotEq|Lt|LtE|Gt|GtE|Is|IsNot|In|NotIn comprehension=(exprtarget,expriter,expr*ifs,intis_async) excepthandler=ExceptHandler(expr?type,identifier?name,stmt*body) attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) arguments=(arg*posonlyargs,arg*args,arg?vararg,arg*kwonlyargs, expr*kw_defaults,arg?kwarg,expr*defaults) arg=(identifierarg,expr?annotation,string?type_comment) attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) --keywordargumentssuppliedtocall(NULLidentifierfor**kwargs) keyword=(identifier?arg,exprvalue) attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) --importnamewithoptional'as'alias. alias=(identifiername,identifier?asname) attributes(intlineno,intcol_offset,int?end_lineno,int?end_col_offset) withitem=(exprcontext_expr,expr?optional_vars) match_case=(patternpattern,expr?guard,stmt*body) pattern=MatchValue(exprvalue) |MatchSingleton(constantvalue) |MatchSequence(pattern*patterns) |MatchMapping(expr*keys,pattern*patterns,identifier?rest) |MatchClass(exprcls,pattern*patterns,identifier*kwd_attrs,pattern*kwd_patterns) |MatchStar(identifier?name) --Theoptional"rest"MatchMappingparameterhandlescapturingextramappingkeys |MatchAs(pattern?pattern,identifier?name) |MatchOr(pattern*patterns) attributes(intlineno,intcol_offset,intend_lineno,intend_col_offset) type_ignore=TypeIgnore(intlineno,stringtag) } Nodeclasses¶ classast.AST¶ ThisisthebaseofallASTnodeclasses.Theactualnodeclassesare derivedfromtheParser/Python.asdlfile,whichisreproduced below.Theyaredefinedinthe_astC moduleandre-exportedinast. Thereisoneclassdefinedforeachleft-handsidesymbolintheabstract grammar(forexample,ast.stmtorast.expr).Inaddition, thereisoneclassdefinedforeachconstructorontheright-handside;these classesinheritfromtheclassesfortheleft-handsidetrees.Forexample, ast.BinOpinheritsfromast.expr.Forproductionrules withalternatives(aka“sums”),theleft-handsideclassisabstract:only instancesofspecificconstructornodesareevercreated. _fields¶ Eachconcreteclasshasanattribute_fieldswhichgivesthenames ofallchildnodes. Eachinstanceofaconcreteclasshasoneattributeforeachchildnode, ofthetypeasdefinedinthegrammar.Forexample,ast.BinOp instanceshaveanattributeleftoftypeast.expr. Iftheseattributesaremarkedasoptionalinthegrammar(usinga questionmark),thevaluemightbeNone.Iftheattributescanhave zero-or-morevalues(markedwithanasterisk),thevaluesarerepresented asPythonlists.Allpossibleattributesmustbepresentandhavevalid valueswhencompilinganASTwithcompile(). lineno¶ col_offset¶ end_lineno¶ end_col_offset¶ Instancesofast.exprandast.stmtsubclasseshave lineno,col_offset,end_lineno,and end_col_offsetattributes.Thelinenoandend_lineno arethefirstandlastlinenumbersofsourcetextspan(1-indexedsothe firstlineisline1)andthecol_offsetandend_col_offset arethecorrespondingUTF-8byteoffsetsofthefirstandlasttokensthat generatedthenode.TheUTF-8offsetisrecordedbecausetheparseruses UTF-8internally. Notethattheendpositionsarenotrequiredbythecompilerandare thereforeoptional.Theendoffsetisafterthelastsymbol,forexample onecangetthesourcesegmentofaone-lineexpressionnodeusing source_line[node.col_offset:node.end_col_offset]. Theconstructorofaclassast.Tparsesitsargumentsasfollows: Iftherearepositionalarguments,theremustbeasmanyasthereareitems inT._fields;theywillbeassignedasattributesofthesenames. Iftherearekeywordarguments,theywillsettheattributesofthesame namestothegivenvalues. Forexample,tocreateandpopulateanast.UnaryOpnode,youcould use node=ast.UnaryOp() node.op=ast.USub() node.operand=ast.Constant() node.operand.value=5 node.operand.lineno=0 node.operand.col_offset=0 node.lineno=0 node.col_offset=0 orthemorecompact node=ast.UnaryOp(ast.USub(),ast.Constant(5,lineno=0,col_offset=0), lineno=0,col_offset=0) Changedinversion3.8:Classast.Constantisnowusedforallconstants. Changedinversion3.9:Simpleindicesarerepresentedbytheirvalue,extendedslicesare representedastuples. Deprecatedsinceversion3.8:Oldclassesast.Num,ast.Str,ast.Bytes, ast.NameConstantandast.Ellipsisarestillavailable, buttheywillberemovedinfuturePythonreleases.Inthemeantime, instantiatingthemwillreturnaninstanceofadifferentclass. Deprecatedsinceversion3.9:Oldclassesast.Indexandast.ExtSlicearestill available,buttheywillberemovedinfuturePythonreleases. Inthemeantime,instantiatingthemwillreturnaninstanceof adifferentclass. Note Thedescriptionsofthespecificnodeclassesdisplayedhere wereinitiallyadaptedfromthefantasticGreenTree Snakesprojectand allitscontributors. Literals¶ classast.Constant(value)¶ Aconstantvalue.ThevalueattributeoftheConstantliteralcontainsthe Pythonobjectitrepresents.Thevaluesrepresentedcanbesimpletypes suchasanumber,stringorNone,butalsoimmutablecontainertypes (tuplesandfrozensets)ifalloftheirelementsareconstant. >>>print(ast.dump(ast.parse('123',mode='eval'),indent=4)) Expression( body=Constant(value=123)) classast.FormattedValue(value,conversion,format_spec)¶ Noderepresentingasingleformattingfieldinanf-string.Ifthestring containsasingleformattingfieldandnothingelsethenodecanbe isolatedotherwiseitappearsinJoinedStr. valueisanyexpressionnode(suchasaliteral,avariable,ora functioncall). conversionisaninteger: -1:noformatting 115:!sstringformatting 114:!rreprformatting 97:!aasciiformatting format_specisaJoinedStrnoderepresentingtheformatting ofthevalue,orNoneifnoformatwasspecified.Both conversionandformat_speccanbesetatthesametime. classast.JoinedStr(values)¶ Anf-string,comprisingaseriesofFormattedValueandConstant nodes. >>>print(ast.dump(ast.parse('f"sin({a})is{sin(a):.3}"',mode='eval'),indent=4)) Expression( body=JoinedStr( values=[ Constant(value='sin('), FormattedValue( value=Name(id='a',ctx=Load()), conversion=-1), Constant(value=')is'), FormattedValue( value=Call( func=Name(id='sin',ctx=Load()), args=[ Name(id='a',ctx=Load())], keywords=[]), conversion=-1, format_spec=JoinedStr( values=[ Constant(value='.3')]))])) classast.List(elts,ctx)¶ classast.Tuple(elts,ctx)¶ Alistortuple.eltsholdsalistofnodesrepresentingtheelements. ctxisStoreifthecontainerisanassignmenttarget(i.e. (x,y)=something),andLoadotherwise. >>>print(ast.dump(ast.parse('[1,2,3]',mode='eval'),indent=4)) Expression( body=List( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load())) >>>print(ast.dump(ast.parse('(1,2,3)',mode='eval'),indent=4)) Expression( body=Tuple( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)], ctx=Load())) classast.Set(elts)¶ Aset.eltsholdsalistofnodesrepresentingtheset’selements. >>>print(ast.dump(ast.parse('{1,2,3}',mode='eval'),indent=4)) Expression( body=Set( elts=[ Constant(value=1), Constant(value=2), Constant(value=3)])) classast.Dict(keys,values)¶ Adictionary.keysandvaluesholdlistsofnodesrepresentingthe keysandthevaluesrespectively,inmatchingorder(whatwouldbereturned whencallingdictionary.keys()anddictionary.values()). Whendoingdictionaryunpackingusingdictionaryliteralstheexpressiontobe expandedgoesinthevalueslist,withaNoneatthecorresponding positioninkeys. >>>print(ast.dump(ast.parse('{"a":1,**d}',mode='eval'),indent=4)) Expression( body=Dict( keys=[ Constant(value='a'), None], values=[ Constant(value=1), Name(id='d',ctx=Load())])) Variables¶ classast.Name(id,ctx)¶ Avariablename.idholdsthenameasastring,andctxisoneof thefollowingtypes. classast.Load¶ classast.Store¶ classast.Del¶ Variablereferencescanbeusedtoloadthevalueofavariable,toassign anewvaluetoit,ortodeleteit.Variablereferencesaregivenacontext todistinguishthesecases. >>>print(ast.dump(ast.parse('a'),indent=4)) Module( body=[ Expr( value=Name(id='a',ctx=Load()))], type_ignores=[]) >>>print(ast.dump(ast.parse('a=1'),indent=4)) Module( body=[ Assign( targets=[ Name(id='a',ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>>print(ast.dump(ast.parse('dela'),indent=4)) Module( body=[ Delete( targets=[ Name(id='a',ctx=Del())])], type_ignores=[]) classast.Starred(value,ctx)¶ A*varvariablereference.valueholdsthevariable,typicallya Namenode.ThistypemustbeusedwhenbuildingaCall nodewith*args. >>>print(ast.dump(ast.parse('a,*b=it'),indent=4)) Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a',ctx=Store()), Starred( value=Name(id='b',ctx=Store()), ctx=Store())], ctx=Store())], value=Name(id='it',ctx=Load()))], type_ignores=[]) Expressions¶ classast.Expr(value)¶ Whenanexpression,suchasafunctioncall,appearsasastatementbyitself withitsreturnvaluenotusedorstored,itiswrappedinthiscontainer. valueholdsoneoftheothernodesinthissection,aConstant,a Name,aLambda,aYieldorYieldFromnode. >>>print(ast.dump(ast.parse('-a'),indent=4)) Module( body=[ Expr( value=UnaryOp( op=USub(), operand=Name(id='a',ctx=Load())))], type_ignores=[]) classast.UnaryOp(op,operand)¶ Aunaryoperation.opistheoperator,andoperandanyexpression node. classast.UAdd¶ classast.USub¶ classast.Not¶ classast.Invert¶ Unaryoperatortokens.Notisthenotkeyword,Invert isthe~operator. >>>print(ast.dump(ast.parse('notx',mode='eval'),indent=4)) Expression( body=UnaryOp( op=Not(), operand=Name(id='x',ctx=Load()))) classast.BinOp(left,op,right)¶ Abinaryoperation(likeadditionordivision).opistheoperator,and leftandrightareanyexpressionnodes. >>>print(ast.dump(ast.parse('x+y',mode='eval'),indent=4)) Expression( body=BinOp( left=Name(id='x',ctx=Load()), op=Add(), right=Name(id='y',ctx=Load()))) classast.Add¶ classast.Sub¶ classast.Mult¶ classast.Div¶ classast.FloorDiv¶ classast.Mod¶ classast.Pow¶ classast.LShift¶ classast.RShift¶ classast.BitOr¶ classast.BitXor¶ classast.BitAnd¶ classast.MatMult¶ Binaryoperatortokens. classast.BoolOp(op,values)¶ Abooleanoperation,‘or’or‘and’.opisOrorAnd. valuesarethevaluesinvolved.Consecutiveoperationswiththesame operator,suchasaorborc,arecollapsedintoonenodewithseveral values. Thisdoesn’tincludenot,whichisaUnaryOp. >>>print(ast.dump(ast.parse('xory',mode='eval'),indent=4)) Expression( body=BoolOp( op=Or(), values=[ Name(id='x',ctx=Load()), Name(id='y',ctx=Load())])) classast.And¶ classast.Or¶ Booleanoperatortokens. classast.Compare(left,ops,comparators)¶ Acomparisonoftwoormorevalues.leftisthefirstvalueinthe comparison,opsthelistofoperators,andcomparatorsthelist ofvaluesafterthefirstelementinthecomparison. >>>print(ast.dump(ast.parse('1<=a<10',mode='eval'),indent=4)) Expression( body=Compare( left=Constant(value=1), ops=[ LtE(), Lt()], comparators=[ Name(id='a',ctx=Load()), Constant(value=10)])) classast.Eq¶ classast.NotEq¶ classast.Lt¶ classast.LtE¶ classast.Gt¶ classast.GtE¶ classast.Is¶ classast.IsNot¶ classast.In¶ classast.NotIn¶ Comparisonoperatortokens. classast.Call(func,args,keywords,starargs,kwargs)¶ Afunctioncall.funcisthefunction,whichwilloftenbea NameorAttributeobject.Ofthearguments: argsholdsalistoftheargumentspassedbyposition. keywordsholdsalistofkeywordobjectsrepresenting argumentspassedbykeyword. WhencreatingaCallnode,argsandkeywordsarerequired,but theycanbeemptylists.starargsandkwargsareoptional. >>>print(ast.dump(ast.parse('func(a,b=c,*d,**e)',mode='eval'),indent=4)) Expression( body=Call( func=Name(id='func',ctx=Load()), args=[ Name(id='a',ctx=Load()), Starred( value=Name(id='d',ctx=Load()), ctx=Load())], keywords=[ keyword( arg='b', value=Name(id='c',ctx=Load())), keyword( value=Name(id='e',ctx=Load()))])) classast.keyword(arg,value)¶ Akeywordargumenttoafunctioncallorclassdefinition.argisaraw stringoftheparametername,valueisanodetopassin. classast.IfExp(test,body,orelse)¶ Anexpressionsuchasaifbelsec.Eachfieldholdsasinglenode,so inthefollowingexample,allthreeareNamenodes. >>>print(ast.dump(ast.parse('aifbelsec',mode='eval'),indent=4)) Expression( body=IfExp( test=Name(id='b',ctx=Load()), body=Name(id='a',ctx=Load()), orelse=Name(id='c',ctx=Load()))) classast.Attribute(value,attr,ctx)¶ Attributeaccess,e.g.d.keys.valueisanode,typicallya Name.attrisabarestringgivingthenameoftheattribute, andctxisLoad,StoreorDelaccordingtohow theattributeisactedon. >>>print(ast.dump(ast.parse('snake.colour',mode='eval'),indent=4)) Expression( body=Attribute( value=Name(id='snake',ctx=Load()), attr='colour', ctx=Load())) classast.NamedExpr(target,value)¶ Anamedexpression.ThisASTnodeisproducedbytheassignmentexpressions operator(alsoknownasthewalrusoperator).AsopposedtotheAssign nodeinwhichthefirstargumentcanbemultiplenodes,inthiscaseboth targetandvaluemustbesinglenodes. >>>print(ast.dump(ast.parse('(x:=4)',mode='eval'),indent=4)) Expression( body=NamedExpr( target=Name(id='x',ctx=Store()), value=Constant(value=4))) Subscripting¶ classast.Subscript(value,slice,ctx)¶ Asubscript,suchasl[1].valueisthesubscriptedobject (usuallysequenceormapping).sliceisanindex,sliceorkey. ItcanbeaTupleandcontainaSlice. ctxisLoad,StoreorDel accordingtotheactionperformedwiththesubscript. >>>print(ast.dump(ast.parse('l[1:2,3]',mode='eval'),indent=4)) Expression( body=Subscript( value=Name(id='l',ctx=Load()), slice=Tuple( elts=[ Slice( lower=Constant(value=1), upper=Constant(value=2)), Constant(value=3)], ctx=Load()), ctx=Load())) classast.Slice(lower,upper,step)¶ Regularslicing(ontheformlower:upperorlower:upper:step). CanoccuronlyinsidetheslicefieldofSubscript,either directlyorasanelementofTuple. >>>print(ast.dump(ast.parse('l[1:2]',mode='eval'),indent=4)) Expression( body=Subscript( value=Name(id='l',ctx=Load()), slice=Slice( lower=Constant(value=1), upper=Constant(value=2)), ctx=Load())) Comprehensions¶ classast.ListComp(elt,generators)¶ classast.SetComp(elt,generators)¶ classast.GeneratorExp(elt,generators)¶ classast.DictComp(key,value,generators)¶ Listandsetcomprehensions,generatorexpressions,anddictionary comprehensions.elt(orkeyandvalue)isasinglenode representingthepartthatwillbeevaluatedforeachitem. generatorsisalistofcomprehensionnodes. >>>print(ast.dump(ast.parse('[xforxinnumbers]',mode='eval'),indent=4)) Expression( body=ListComp( elt=Name(id='x',ctx=Load()), generators=[ comprehension( target=Name(id='x',ctx=Store()), iter=Name(id='numbers',ctx=Load()), ifs=[], is_async=0)])) >>>print(ast.dump(ast.parse('{x:x**2forxinnumbers}',mode='eval'),indent=4)) Expression( body=DictComp( key=Name(id='x',ctx=Load()), value=BinOp( left=Name(id='x',ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='x',ctx=Store()), iter=Name(id='numbers',ctx=Load()), ifs=[], is_async=0)])) >>>print(ast.dump(ast.parse('{xforxinnumbers}',mode='eval'),indent=4)) Expression( body=SetComp( elt=Name(id='x',ctx=Load()), generators=[ comprehension( target=Name(id='x',ctx=Store()), iter=Name(id='numbers',ctx=Load()), ifs=[], is_async=0)])) classast.comprehension(target,iter,ifs,is_async)¶ Oneforclauseinacomprehension.targetisthereferencetousefor eachelement-typicallyaNameorTuplenode.iter istheobjecttoiterateover.ifsisalistoftestexpressions:each forclausecanhavemultipleifs. is_asyncindicatesacomprehensionisasynchronous(usingan asyncforinsteadoffor).Thevalueisaninteger(0or1). >>>print(ast.dump(ast.parse('[ord(c)forlineinfileforcinline]',mode='eval'), ...indent=4))#Multiplecomprehensionsinone. Expression( body=ListComp( elt=Call( func=Name(id='ord',ctx=Load()), args=[ Name(id='c',ctx=Load())], keywords=[]), generators=[ comprehension( target=Name(id='line',ctx=Store()), iter=Name(id='file',ctx=Load()), ifs=[], is_async=0), comprehension( target=Name(id='c',ctx=Store()), iter=Name(id='line',ctx=Load()), ifs=[], is_async=0)])) >>>print(ast.dump(ast.parse('(n**2forninitifn>5ifn<10)',mode='eval'), ...indent=4))#generatorcomprehension Expression( body=GeneratorExp( elt=BinOp( left=Name(id='n',ctx=Load()), op=Pow(), right=Constant(value=2)), generators=[ comprehension( target=Name(id='n',ctx=Store()), iter=Name(id='it',ctx=Load()), ifs=[ Compare( left=Name(id='n',ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), Compare( left=Name(id='n',ctx=Load()), ops=[ Lt()], comparators=[ Constant(value=10)])], is_async=0)])) >>>print(ast.dump(ast.parse('[iasyncforiinsoc]',mode='eval'), ...indent=4))#Asynccomprehension Expression( body=ListComp( elt=Name(id='i',ctx=Load()), generators=[ comprehension( target=Name(id='i',ctx=Store()), iter=Name(id='soc',ctx=Load()), ifs=[], is_async=1)])) Statements¶ classast.Assign(targets,value,type_comment)¶ Anassignment.targetsisalistofnodes,andvalueisasinglenode. Multiplenodesintargetsrepresentsassigningthesamevaluetoeach. UnpackingisrepresentedbyputtingaTupleorList withintargets. type_comment¶ type_commentisanoptionalstringwiththetypeannotationasacomment. >>>print(ast.dump(ast.parse('a=b=1'),indent=4))#Multipleassignment Module( body=[ Assign( targets=[ Name(id='a',ctx=Store()), Name(id='b',ctx=Store())], value=Constant(value=1))], type_ignores=[]) >>>print(ast.dump(ast.parse('a,b=c'),indent=4))#Unpacking Module( body=[ Assign( targets=[ Tuple( elts=[ Name(id='a',ctx=Store()), Name(id='b',ctx=Store())], ctx=Store())], value=Name(id='c',ctx=Load()))], type_ignores=[]) classast.AnnAssign(target,annotation,value,simple)¶ Anassignmentwithatypeannotation.targetisasinglenodeandcan beaName,aAttributeoraSubscript. annotationistheannotation,suchasaConstantorName node.valueisasingleoptionalnode.simpleisabooleaninteger settoTrueforaNamenodeintargetthatdonotappearin betweenparenthesisandarehencepurenamesandnotexpressions. >>>print(ast.dump(ast.parse('c:int'),indent=4)) Module( body=[ AnnAssign( target=Name(id='c',ctx=Store()), annotation=Name(id='int',ctx=Load()), simple=1)], type_ignores=[]) >>>print(ast.dump(ast.parse('(a):int=1'),indent=4))#Annotationwithparenthesis Module( body=[ AnnAssign( target=Name(id='a',ctx=Store()), annotation=Name(id='int',ctx=Load()), value=Constant(value=1), simple=0)], type_ignores=[]) >>>print(ast.dump(ast.parse('a.b:int'),indent=4))#Attributeannotation Module( body=[ AnnAssign( target=Attribute( value=Name(id='a',ctx=Load()), attr='b', ctx=Store()), annotation=Name(id='int',ctx=Load()), simple=0)], type_ignores=[]) >>>print(ast.dump(ast.parse('a[1]:int'),indent=4))#Subscriptannotation Module( body=[ AnnAssign( target=Subscript( value=Name(id='a',ctx=Load()), slice=Constant(value=1), ctx=Store()), annotation=Name(id='int',ctx=Load()), simple=0)], type_ignores=[]) classast.AugAssign(target,op,value)¶ Augmentedassignment,suchasa+=1.Inthefollowingexample, targetisaNamenodeforx(withtheStore context),opisAdd,andvalueisaConstantwith valuefor1. ThetargetattributecannotbeofclassTupleorList, unlikethetargetsofAssign. >>>print(ast.dump(ast.parse('x+=2'),indent=4)) Module( body=[ AugAssign( target=Name(id='x',ctx=Store()), op=Add(), value=Constant(value=2))], type_ignores=[]) classast.Raise(exc,cause)¶ Araisestatement.excistheexceptionobjecttoberaised,normallya CallorName,orNoneforastandaloneraise. causeistheoptionalpartforyinraisexfromy. >>>print(ast.dump(ast.parse('raisexfromy'),indent=4)) Module( body=[ Raise( exc=Name(id='x',ctx=Load()), cause=Name(id='y',ctx=Load()))], type_ignores=[]) classast.Assert(test,msg)¶ Anassertion.testholdsthecondition,suchasaComparenode. msgholdsthefailuremessage. >>>print(ast.dump(ast.parse('assertx,y'),indent=4)) Module( body=[ Assert( test=Name(id='x',ctx=Load()), msg=Name(id='y',ctx=Load()))], type_ignores=[]) classast.Delete(targets)¶ Representsadelstatement.targetsisalistofnodes,suchas Name,AttributeorSubscriptnodes. >>>print(ast.dump(ast.parse('delx,y,z'),indent=4)) Module( body=[ Delete( targets=[ Name(id='x',ctx=Del()), Name(id='y',ctx=Del()), Name(id='z',ctx=Del())])], type_ignores=[]) classast.Pass¶ Apassstatement. >>>print(ast.dump(ast.parse('pass'),indent=4)) Module( body=[ Pass()], type_ignores=[]) Otherstatementswhichareonlyapplicableinsidefunctionsorloopsare describedinothersections. Imports¶ classast.Import(names)¶ Animportstatement.namesisalistofaliasnodes. >>>print(ast.dump(ast.parse('importx,y,z'),indent=4)) Module( body=[ Import( names=[ alias(name='x'), alias(name='y'), alias(name='z')])], type_ignores=[]) classast.ImportFrom(module,names,level)¶ Representsfromximporty.moduleisarawstringofthe‘from’name, withoutanyleadingdots,orNoneforstatementssuchasfrom.importfoo. levelisanintegerholdingtheleveloftherelativeimport(0means absoluteimport). >>>print(ast.dump(ast.parse('fromyimportx,y,z'),indent=4)) Module( body=[ ImportFrom( module='y', names=[ alias(name='x'), alias(name='y'), alias(name='z')], level=0)], type_ignores=[]) classast.alias(name,asname)¶ Bothparametersarerawstringsofthenames.asnamecanbeNoneif theregularnameistobeused. >>>print(ast.dump(ast.parse('from..foo.barimportaasb,c'),indent=4)) Module( body=[ ImportFrom( module='foo.bar', names=[ alias(name='a',asname='b'), alias(name='c')], level=2)], type_ignores=[]) Controlflow¶ Note Optionalclausessuchaselsearestoredasanemptylistifthey’re notpresent. classast.If(test,body,orelse)¶ Anifstatement.testholdsasinglenode,suchasaCompare node.bodyandorelseeachholdalistofnodes. elifclausesdon’thaveaspecialrepresentationintheAST,butrather appearasextraIfnodeswithintheorelsesectionofthe previousone. >>>print(ast.dump(ast.parse(""" ...ifx: ...... ...elify: ...... ...else: ...... ..."""),indent=4)) Module( body=[ If( test=Name(id='x',ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ If( test=Name(id='y',ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.For(target,iter,body,orelse,type_comment)¶ Aforloop.targetholdsthevariable(s)theloopassignsto,asa singleName,TupleorListnode.iterholds theitemtobeloopedover,againasasinglenode.bodyandorelse containlistsofnodestoexecute.Thoseinorelseareexecutedifthe loopfinishesnormally,ratherthanviaabreakstatement. type_comment¶ type_commentisanoptionalstringwiththetypeannotationasacomment. >>>print(ast.dump(ast.parse(""" ...forxiny: ...... ...else: ...... ..."""),indent=4)) Module( body=[ For( target=Name(id='x',ctx=Store()), iter=Name(id='y',ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) classast.While(test,body,orelse)¶ Awhileloop.testholdsthecondition,suchasaCompare node. >>print(ast.dump(ast.parse(""" ...whilex: ...... ...else: ...... ..."""),indent=4)) Module( body=[ While( test=Name(id='x',ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))], orelse=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) classast.Break¶ classast.Continue¶ Thebreakandcontinuestatements. >>>print(ast.dump(ast.parse("""\ ...forainb: ...ifa>5: ...break ...else: ...continue ... ..."""),indent=4)) Module( body=[ For( target=Name(id='a',ctx=Store()), iter=Name(id='b',ctx=Load()), body=[ If( test=Compare( left=Name(id='a',ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=5)]), body=[ Break()], orelse=[ Continue()])], orelse=[])], type_ignores=[]) classast.Try(body,handlers,orelse,finalbody)¶ tryblocks.Allattributesarelistofnodestoexecute,exceptfor handlers,whichisalistofExceptHandlernodes. >>>print(ast.dump(ast.parse(""" ...try: ...... ...exceptException: ...... ...exceptOtherExceptionase: ...... ...else: ...... ...finally: ...... ..."""),indent=4)) Module( body=[ Try( body=[ Expr( value=Constant(value=Ellipsis))], handlers=[ ExceptHandler( type=Name(id='Exception',ctx=Load()), body=[ Expr( value=Constant(value=Ellipsis))]), ExceptHandler( type=Name(id='OtherException',ctx=Load()), name='e', body=[ Expr( value=Constant(value=Ellipsis))])], orelse=[ Expr( value=Constant(value=Ellipsis))], finalbody=[ Expr( value=Constant(value=Ellipsis))])], type_ignores=[]) classast.ExceptHandler(type,name,body)¶ Asingleexceptclause.typeistheexceptiontypeitwillmatch, typicallyaNamenode(orNoneforacatch-allexcept:clause). nameisarawstringforthenametoholdtheexception,orNoneif theclausedoesn’thaveasfoo.bodyisalistofnodes. >>>print(ast.dump(ast.parse("""\ ...try: ...a+1 ...exceptTypeError: ...pass ..."""),indent=4)) Module( body=[ Try( body=[ Expr( value=BinOp( left=Name(id='a',ctx=Load()), op=Add(), right=Constant(value=1)))], handlers=[ ExceptHandler( type=Name(id='TypeError',ctx=Load()), body=[ Pass()])], orelse=[], finalbody=[])], type_ignores=[]) classast.With(items,body,type_comment)¶ Awithblock.itemsisalistofwithitemnodesrepresenting thecontextmanagers,andbodyistheindentedblockinsidethecontext. type_comment¶ type_commentisanoptionalstringwiththetypeannotationasacomment. classast.withitem(context_expr,optional_vars)¶ Asinglecontextmanagerinawithblock.context_expristhecontext manager,oftenaCallnode.optional_varsisaName, TupleorListfortheasfoopart,orNoneifthat isn’tused. >>>print(ast.dump(ast.parse("""\ ...withaasb,casd: ...something(b,d) ..."""),indent=4)) Module( body=[ With( items=[ withitem( context_expr=Name(id='a',ctx=Load()), optional_vars=Name(id='b',ctx=Store())), withitem( context_expr=Name(id='c',ctx=Load()), optional_vars=Name(id='d',ctx=Store()))], body=[ Expr( value=Call( func=Name(id='something',ctx=Load()), args=[ Name(id='b',ctx=Load()), Name(id='d',ctx=Load())], keywords=[]))])], type_ignores=[]) Patternmatching¶ classast.Match(subject,cases)¶ Amatchstatement.subjectholdsthesubjectofthematch(theobject thatisbeingmatchedagainstthecases)andcasescontainsaniterableof match_casenodeswiththedifferentcases. classast.match_case(pattern,guard,body)¶ Asinglecasepatterninamatchstatement.patterncontainsthe matchpatternthatthesubjectwillbematchedagainst.Notethatthe ASTnodesproducedforpatternsdifferfromthoseproducedfor expressions,evenwhentheysharethesamesyntax. Theguardattributecontainsanexpressionthatwillbeevaluatedif thepatternmatchesthesubject. bodycontainsalistofnodestoexecuteifthepatternmatchesand theresultofevaluatingtheguardexpressionistrue. >>>print(ast.dump(ast.parse(""" ...matchx: ...case[x]ifx>0: ...... ...casetuple(): ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), guard=Compare( left=Name(id='x',ctx=Load()), ops=[ Gt()], comparators=[ Constant(value=0)]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='tuple',ctx=Load()), patterns=[], kwd_attrs=[], kwd_patterns=[]), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchValue(value)¶ Amatchliteralorvaluepatternthatcomparesbyequality.valueis anexpressionnode.Permittedvaluenodesarerestrictedasdescribedin thematchstatementdocumentation.Thispatternsucceedsifthematch subjectisequaltotheevaluatedvalue. >>>print(ast.dump(ast.parse(""" ...matchx: ...case"Relevant": ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchValue( value=Constant(value='Relevant')), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchSingleton(value)¶ Amatchliteralpatternthatcomparesbyidentity.valueisthe singletontobecomparedagainst:None,True,orFalse.This patternsucceedsifthematchsubjectisthegivenconstant. >>>print(ast.dump(ast.parse(""" ...matchx: ...caseNone: ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchSingleton(value=None), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchSequence(patterns)¶ Amatchsequencepattern.patternscontainsthepatternstobematched againstthesubjectelementsifthesubjectisasequence.Matchesavariable lengthsequenceifoneofthesubpatternsisaMatchStarnode,otherwise matchesafixedlengthsequence. >>>print(ast.dump(ast.parse(""" ...matchx: ...case[1,2]: ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2))]), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchStar(name)¶ Matchestherestofthesequenceinavariablelengthmatchsequencepattern. IfnameisnotNone,alistcontainingtheremainingsequence elementsisboundtothatnameiftheoverallsequencepatternissuccessful. >>>print(ast.dump(ast.parse(""" ...matchx: ...case[1,2,*rest]: ...... ...case[*_]: ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchSequence( patterns=[ MatchValue( value=Constant(value=1)), MatchValue( value=Constant(value=2)), MatchStar(name='rest')]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchSequence( patterns=[ MatchStar()]), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchMapping(keys,patterns,rest)¶ Amatchmappingpattern.keysisasequenceofexpressionnodes. patternsisacorrespondingsequenceofpatternnodes.restisan optionalnamethatcanbespecifiedtocapturetheremainingmappingelements. Permittedkeyexpressionsarerestrictedasdescribedinthematchstatement documentation. Thispatternsucceedsifthesubjectisamapping,allevaluatedkey expressionsarepresentinthemapping,andthevaluecorrespondingtoeach keymatchesthecorrespondingsubpattern.IfrestisnotNone,adict containingtheremainingmappingelementsisboundtothatnameiftheoverall mappingpatternissuccessful. >>>print(ast.dump(ast.parse(""" ...matchx: ...case{1:_,2:_}: ...... ...case{**rest}: ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchMapping( keys=[ Constant(value=1), Constant(value=2)], patterns=[ MatchAs(), MatchAs()]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchMapping(keys=[],patterns=[],rest='rest'), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchClass(cls,patterns,kwd_attrs,kwd_patterns)¶ Amatchclasspattern.clsisanexpressiongivingthenominalclassto bematched.patternsisasequenceofpatternnodestobematchedagainst theclassdefinedsequenceofpatternmatchingattributes.kwd_attrsisa sequenceofadditionalattributestobematched(specifiedaskeywordarguments intheclasspattern),kwd_patternsarethecorrespondingpatterns (specifiedaskeywordvaluesintheclasspattern). Thispatternsucceedsifthesubjectisaninstanceofthenominatedclass, allpositionalpatternsmatchthecorrespondingclass-definedattributes,and anyspecifiedkeywordattributesmatchtheircorrespondingpattern. Note:classesmaydefineapropertythatreturnsselfinordertomatcha patternnodeagainsttheinstancebeingmatched.Severalbuiltintypesare alsomatchedthatway,asdescribedinthematchstatementdocumentation. >>>print(ast.dump(ast.parse(""" ...matchx: ...casePoint2D(0,0): ...... ...casePoint3D(x=0,y=0,z=0): ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchClass( cls=Name(id='Point2D',ctx=Load()), patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))], kwd_attrs=[], kwd_patterns=[]), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchClass( cls=Name(id='Point3D',ctx=Load()), patterns=[], kwd_attrs=[ 'x', 'y', 'z'], kwd_patterns=[ MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0)), MatchValue( value=Constant(value=0))]), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchAs(pattern,name)¶ Amatch“as-pattern”,capturepatternorwildcardpattern.pattern containsthematchpatternthatthesubjectwillbematchedagainst. IfthepatternisNone,thenoderepresentsacapturepattern(i.ea barename)andwillalwayssucceed. Thenameattributecontainsthenamethatwillbeboundifthepattern issuccessful.IfnameisNone,patternmustalsobeNone andthenoderepresentsthewildcardpattern. >>>print(ast.dump(ast.parse(""" ...matchx: ...case[x]asy: ...... ...case_: ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchAs( pattern=MatchSequence( patterns=[ MatchAs(name='x')]), name='y'), body=[ Expr( value=Constant(value=Ellipsis))]), match_case( pattern=MatchAs(), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) classast.MatchOr(patterns)¶ Amatch“or-pattern”.Anor-patternmatcheseachofitssubpatternsinturn tothesubject,untilonesucceeds.Theor-patternisthendeemedto succeed.Ifnoneofthesubpatternssucceedtheor-patternfails.The patternsattributecontainsalistofmatchpatternnodesthatwillbe matchedagainstthesubject. >>>print(ast.dump(ast.parse(""" ...matchx: ...case[x]|(y): ...... ..."""),indent=4)) Module( body=[ Match( subject=Name(id='x',ctx=Load()), cases=[ match_case( pattern=MatchOr( patterns=[ MatchSequence( patterns=[ MatchAs(name='x')]), MatchAs(name='y')]), body=[ Expr( value=Constant(value=Ellipsis))])])], type_ignores=[]) Functionandclassdefinitions¶ classast.FunctionDef(name,args,body,decorator_list,returns,type_comment)¶ Afunctiondefinition. nameisarawstringofthefunctionname. argsisanargumentsnode. bodyisthelistofnodesinsidethefunction. decorator_lististhelistofdecoratorstobeapplied,storedoutermost first(i.e.thefirstinthelistwillbeappliedlast). returnsisthereturnannotation. type_comment¶ type_commentisanoptionalstringwiththetypeannotationasacomment. classast.Lambda(args,body)¶ lambdaisaminimalfunctiondefinitionthatcanbeusedinsidean expression.UnlikeFunctionDef,bodyholdsasinglenode. >>>print(ast.dump(ast.parse('lambdax,y:...'),indent=4)) Module( body=[ Expr( value=Lambda( args=arguments( posonlyargs=[], args=[ arg(arg='x'), arg(arg='y')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=Constant(value=Ellipsis)))], type_ignores=[]) classast.arguments(posonlyargs,args,vararg,kwonlyargs,kw_defaults,kwarg,defaults)¶ Theargumentsforafunction. posonlyargs,argsandkwonlyargsarelistsofargnodes. varargandkwargaresingleargnodes,referringtothe *args,**kwargsparameters. kw_defaultsisalistofdefaultvaluesforkeyword-onlyarguments.If oneisNone,thecorrespondingargumentisrequired. defaultsisalistofdefaultvaluesforargumentsthatcanbepassed positionally.Iftherearefewerdefaults,theycorrespondtothelastn arguments. classast.arg(arg,annotation,type_comment)¶ Asingleargumentinalist.argisarawstringoftheargument name,annotationisitsannotation,suchasaStror Namenode. type_comment¶ type_commentisanoptionalstringwiththetypeannotationasacomment >>>print(ast.dump(ast.parse("""\ ...@decorator1 ...@decorator2 ...deff(a:'annotation',b=1,c=2,*d,e,f=3,**g)->'returnannotation': ...pass ..."""),indent=4)) Module( body=[ FunctionDef( name='f', args=arguments( posonlyargs=[], args=[ arg( arg='a', annotation=Constant(value='annotation')), arg(arg='b'), arg(arg='c')], vararg=arg(arg='d'), kwonlyargs=[ arg(arg='e'), arg(arg='f')], kw_defaults=[ None, Constant(value=3)], kwarg=arg(arg='g'), defaults=[ Constant(value=1), Constant(value=2)]), body=[ Pass()], decorator_list=[ Name(id='decorator1',ctx=Load()), Name(id='decorator2',ctx=Load())], returns=Constant(value='returnannotation'))], type_ignores=[]) classast.Return(value)¶ Areturnstatement. >>>print(ast.dump(ast.parse('return4'),indent=4)) Module( body=[ Return( value=Constant(value=4))], type_ignores=[]) classast.Yield(value)¶ classast.YieldFrom(value)¶ Ayieldoryieldfromexpression.Becausetheseareexpressions,they mustbewrappedinaExprnodeifthevaluesentbackisnotused. >>>print(ast.dump(ast.parse('yieldx'),indent=4)) Module( body=[ Expr( value=Yield( value=Name(id='x',ctx=Load())))], type_ignores=[]) >>>print(ast.dump(ast.parse('yieldfromx'),indent=4)) Module( body=[ Expr( value=YieldFrom( value=Name(id='x',ctx=Load())))], type_ignores=[]) classast.Global(names)¶ classast.Nonlocal(names)¶ globalandnonlocalstatements.namesisalistofrawstrings. >>>print(ast.dump(ast.parse('globalx,y,z'),indent=4)) Module( body=[ Global( names=[ 'x', 'y', 'z'])], type_ignores=[]) >>>print(ast.dump(ast.parse('nonlocalx,y,z'),indent=4)) Module( body=[ Nonlocal( names=[ 'x', 'y', 'z'])], type_ignores=[]) classast.ClassDef(name,bases,keywords,starargs,kwargs,body,decorator_list)¶ Aclassdefinition. nameisarawstringfortheclassname basesisalistofnodesforexplicitlyspecifiedbaseclasses. keywordsisalistofkeywordnodes,principallyfor‘metaclass’. Otherkeywordswillbepassedtothemetaclass,asperPEP-3115. starargsandkwargsareeachasinglenode,asinafunctioncall. starargswillbeexpandedtojointhelistofbaseclasses,andkwargswill bepassedtothemetaclass. bodyisalistofnodesrepresentingthecodewithintheclass definition. decorator_listisalistofnodes,asinFunctionDef. >>>print(ast.dump(ast.parse("""\ ...@decorator1 ...@decorator2 ...classFoo(base1,base2,metaclass=meta): ...pass ..."""),indent=4)) Module( body=[ ClassDef( name='Foo', bases=[ Name(id='base1',ctx=Load()), Name(id='base2',ctx=Load())], keywords=[ keyword( arg='metaclass', value=Name(id='meta',ctx=Load()))], body=[ Pass()], decorator_list=[ Name(id='decorator1',ctx=Load()), Name(id='decorator2',ctx=Load())])], type_ignores=[]) Asyncandawait¶ classast.AsyncFunctionDef(name,args,body,decorator_list,returns,type_comment)¶ Anasyncdeffunctiondefinition.Hasthesamefieldsas FunctionDef. classast.Await(value)¶ Anawaitexpression.valueiswhatitwaitsfor. OnlyvalidinthebodyofanAsyncFunctionDef. >>>print(ast.dump(ast.parse("""\ ...asyncdeff(): ...awaitother_func() ..."""),indent=4)) Module( body=[ AsyncFunctionDef( name='f', args=arguments( posonlyargs=[], args=[], kwonlyargs=[], kw_defaults=[], defaults=[]), body=[ Expr( value=Await( value=Call( func=Name(id='other_func',ctx=Load()), args=[], keywords=[])))], decorator_list=[])], type_ignores=[]) classast.AsyncFor(target,iter,body,orelse,type_comment)¶ classast.AsyncWith(items,body,type_comment)¶ asyncforloopsandasyncwithcontextmanagers.Theyhavethesame fieldsasForandWith,respectively.Onlyvalidinthe bodyofanAsyncFunctionDef. Note Whenastringisparsedbyast.parse(),operatornodes(subclasses ofast.operator,ast.unaryop,ast.cmpop, ast.boolopandast.expr_context)onthereturnedtree willbesingletons.Changestoonewillbereflectedinallother occurrencesofthesamevalue(e.g.ast.Add). astHelpers¶ Apartfromthenodeclasses,theastmoduledefinestheseutilityfunctions andclassesfortraversingabstractsyntaxtrees: ast.parse(source,filename='',mode='exec',*,type_comments=False,feature_version=None)¶ ParsethesourceintoanASTnode.Equivalenttocompile(source, filename,mode,ast.PyCF_ONLY_AST). Iftype_comments=Trueisgiven,theparserismodifiedtocheck andreturntypecommentsasspecifiedbyPEP484andPEP526. Thisisequivalenttoaddingast.PyCF_TYPE_COMMENTStothe flagspassedtocompile().Thiswillreportsyntaxerrors formisplacedtypecomments.Withoutthisflag,typecommentswill beignored,andthetype_commentfieldonselectedASTnodes willalwaysbeNone.Inaddition,thelocationsof#type: ignorecommentswillbereturnedasthetype_ignores attributeofModule(otherwiseitisalwaysanemptylist). Inaddition,ifmodeis'func_type',theinputsyntaxis modifiedtocorrespondtoPEP484“signaturetypecomments”, e.g.(str,int)->List[str]. Also,settingfeature_versiontoatuple(major,minor) willattempttoparseusingthatPythonversion’sgrammar. Currentlymajormustequalto3.Forexample,setting feature_version=(3,4)willallowtheuseofasyncand awaitasvariablenames.Thelowestsupportedversionis (3,4);thehighestissys.version_info[0:2]. Ifsourcecontainsanullcharacter(’0’),ValueErrorisraised. Warning NotethatsuccessfullyparsingsourcecodeintoanASTobjectdoesn’t guaranteethatthesourcecodeprovidedisvalidPythoncodethatcan beexecutedasthecompilationstepcanraisefurtherSyntaxError exceptions.Forinstance,thesourcereturn42generatesavalid ASTnodeforareturnstatement,butitcannotbecompiledalone(itneeds tobeinsideafunctionnode). Inparticular,ast.parse()won’tdoanyscopingchecks,whichthe compilationstepdoes. Warning ItispossibletocrashthePythoninterpreterwitha sufficientlylarge/complexstringduetostackdepthlimitations inPython’sASTcompiler. Changedinversion3.8:Addedtype_comments,mode='func_type'andfeature_version. ast.unparse(ast_obj)¶ Unparseanast.ASTobjectandgenerateastringwithcode thatwouldproduceanequivalentast.ASTobjectifparsed backwithast.parse(). Warning Theproducedcodestringwillnotnecessarilybeequaltotheoriginal codethatgeneratedtheast.ASTobject(withoutanycompiler optimizations,suchasconstanttuples/frozensets). Warning Tryingtounparseahighlycomplexexpressionwouldresultwith RecursionError. Newinversion3.9. ast.literal_eval(node_or_string)¶ SafelyevaluateanexpressionnodeorastringcontainingaPythonliteralor containerdisplay.Thestringornodeprovidedmayonlyconsistofthe followingPythonliteralstructures:strings,bytes,numbers,tuples,lists, dicts,sets,booleans,NoneandEllipsis. ThiscanbeusedforsafelyevaluatingstringscontainingPythonvaluesfrom untrustedsourceswithouttheneedtoparsethevaluesoneself.Itisnot capableofevaluatingarbitrarilycomplexexpressions,forexampleinvolving operatorsorindexing. Warning ItispossibletocrashthePythoninterpreterwitha sufficientlylarge/complexstringduetostackdepthlimitations inPython’sASTcompiler. ItcanraiseValueError,TypeError,SyntaxError, MemoryErrorandRecursionErrordependingonthemalformed input. Changedinversion3.2:Nowallowsbytesandsetliterals. Changedinversion3.9:Nowsupportscreatingemptysetswith'set()'. Changedinversion3.10:Forstringinputs,leadingspacesandtabsarenowstripped. ast.get_docstring(node,clean=True)¶ Returnthedocstringofthegivennode(whichmustbea FunctionDef,AsyncFunctionDef,ClassDef, orModulenode),orNoneifithasnodocstring. Ifcleanistrue,cleanupthedocstring’sindentationwith inspect.cleandoc(). Changedinversion3.5:AsyncFunctionDefisnowsupported. ast.get_source_segment(source,node,*,padded=False)¶ Getsourcecodesegmentofthesourcethatgeneratednode. Ifsomelocationinformation(lineno,end_lineno, col_offset,orend_col_offset)ismissing,returnNone. IfpaddedisTrue,thefirstlineofamulti-linestatementwill bepaddedwithspacestomatchitsoriginalposition. Newinversion3.8. ast.fix_missing_locations(node)¶ Whenyoucompileanodetreewithcompile(),thecompilerexpects linenoandcol_offsetattributesforeverynodethatsupports them.Thisisrathertedioustofillinforgeneratednodes,sothishelper addstheseattributesrecursivelywherenotalreadyset,bysettingthemto thevaluesoftheparentnode.Itworksrecursivelystartingatnode. ast.increment_lineno(node,n=1)¶ Incrementthelinenumberandendlinenumberofeachnodeinthetree startingatnodebyn.Thisisusefulto“movecode”toadifferent locationinafile. ast.copy_location(new_node,old_node)¶ Copysourcelocation(lineno,col_offset,end_lineno, andend_col_offset)fromold_nodetonew_nodeifpossible, andreturnnew_node. ast.iter_fields(node)¶ Yieldatupleof(fieldname,value)foreachfieldinnode._fields thatispresentonnode. ast.iter_child_nodes(node)¶ Yieldalldirectchildnodesofnode,thatis,allfieldsthatarenodes andallitemsoffieldsthatarelistsofnodes. ast.walk(node)¶ Recursivelyyieldalldescendantnodesinthetreestartingatnode (includingnodeitself),innospecifiedorder.Thisisusefulifyouonly wanttomodifynodesinplaceanddon’tcareaboutthecontext. classast.NodeVisitor¶ Anodevisitorbaseclassthatwalkstheabstractsyntaxtreeandcallsa visitorfunctionforeverynodefound.Thisfunctionmayreturnavalue whichisforwardedbythevisit()method. Thisclassismeanttobesubclassed,withthesubclassaddingvisitor methods. visit(node)¶ Visitanode.Thedefaultimplementationcallsthemethodcalled self.visit_classnamewhereclassnameisthenameofthenode class,orgeneric_visit()ifthatmethoddoesn’texist. generic_visit(node)¶ Thisvisitorcallsvisit()onallchildrenofthenode. Notethatchildnodesofnodesthathaveacustomvisitormethodwon’tbe visitedunlessthevisitorcallsgeneric_visit()orvisitsthem itself. Don’tusetheNodeVisitorifyouwanttoapplychangestonodes duringtraversal.Forthisaspecialvisitorexists (NodeTransformer)thatallowsmodifications. Deprecatedsinceversion3.8:Methodsvisit_Num(),visit_Str(),visit_Bytes(), visit_NameConstant()andvisit_Ellipsis()aredeprecated nowandwillnotbecalledinfuturePythonversions.Addthe visit_Constant()methodtohandleallconstantnodes. classast.NodeTransformer¶ ANodeVisitorsubclassthatwalkstheabstractsyntaxtreeand allowsmodificationofnodes. TheNodeTransformerwillwalktheASTandusethereturnvalueof thevisitormethodstoreplaceorremovetheoldnode.Ifthereturnvalue ofthevisitormethodisNone,thenodewillberemovedfromits location,otherwiseitisreplacedwiththereturnvalue.Thereturnvalue maybetheoriginalnodeinwhichcasenoreplacementtakesplace. Hereisanexampletransformerthatrewritesalloccurrencesofnamelookups (foo)todata['foo']: classRewriteName(NodeTransformer): defvisit_Name(self,node): returnSubscript( value=Name(id='data',ctx=Load()), slice=Constant(value=node.id), ctx=node.ctx ) Keepinmindthatifthenodeyou’reoperatingonhaschildnodesyoumust eithertransformthechildnodesyourselforcallthegeneric_visit() methodforthenodefirst. Fornodesthatwerepartofacollectionofstatements(thatappliestoall statementnodes),thevisitormayalsoreturnalistofnodesratherthan justasinglenode. IfNodeTransformerintroducesnewnodes(thatweren’tpartof originaltree)withoutgivingthemlocationinformation(suchas lineno),fix_missing_locations()shouldbecalledwith thenewsub-treetorecalculatethelocationinformation: tree=ast.parse('foo',mode='eval') new_tree=fix_missing_locations(RewriteName().visit(tree)) Usuallyyouusethetransformerlikethis: node=YourTransformer().visit(node) ast.dump(node,annotate_fields=True,include_attributes=False,*,indent=None)¶ Returnaformatteddumpofthetreeinnode.Thisismainlyusefulfor debuggingpurposes.Ifannotate_fieldsistrue(bydefault), thereturnedstringwillshowthenamesandthevaluesforfields. Ifannotate_fieldsisfalse,theresultstringwillbemorecompactby omittingunambiguousfieldnames.Attributessuchasline numbersandcolumnoffsetsarenotdumpedbydefault.Ifthisiswanted, include_attributescanbesettotrue. Ifindentisanon-negativeintegerorstring,thenthetreewillbe pretty-printedwiththatindentlevel.Anindentlevel of0,negative,or""willonlyinsertnewlines.None(thedefault) selectsthesinglelinerepresentation.Usingapositiveintegerindent indentsthatmanyspacesperlevel.Ifindentisastring(suchas"\t"), thatstringisusedtoindenteachlevel. Changedinversion3.9:Addedtheindentoption. CompilerFlags¶ Thefollowingflagsmaybepassedtocompile()inordertochange effectsonthecompilationofaprogram: ast.PyCF_ALLOW_TOP_LEVEL_AWAIT¶ Enablessupportfortop-levelawait,asyncfor,asyncwith andasynccomprehensions. Newinversion3.8. ast.PyCF_ONLY_AST¶ Generatesandreturnsanabstractsyntaxtreeinsteadofreturninga compiledcodeobject. ast.PyCF_TYPE_COMMENTS¶ EnablessupportforPEP484andPEP526styletypecomments (#type:,#type:ignore). Newinversion3.8. Command-LineUsage¶ Newinversion3.9. Theastmodulecanbeexecutedasascriptfromthecommandline. Itisassimpleas: python-mast[-m][-a][infile] Thefollowingoptionsareaccepted: -h,--help¶ Showthehelpmessageandexit. -m¶ --mode¶ Specifywhatkindofcodemustbecompiled,likethemodeargument inparse(). --no-type-comments¶ Don’tparsetypecomments. -a,--include-attributes¶ Includeattributessuchaslinenumbersandcolumnoffsets. -i¶ --indent¶ IndentationofnodesinAST(numberofspaces). IfinfileisspecifieditscontentsareparsedtoASTanddumped tostdout.Otherwise,thecontentisreadfromstdin. Seealso GreenTreeSnakes,anexternal documentationresource,hasgooddetailsonworkingwithPythonASTs. ASTTokens annotatesPythonASTswiththepositionsoftokensandtextinthesource codethatgeneratedthem.Thisishelpfulfortoolsthatmakesourcecode transformations. leoAst.pyunifiesthe token-basedandparse-tree-basedviewsofpythonprogramsbyinserting two-waylinksbetweentokensandastnodes. LibCSTparsescodeasaConcreteSyntax Treethatlookslikeanasttreeandkeepsallformattingdetails.It’s usefulforbuildingautomatedrefactoring(codemod)applicationsand linters. ParsoisaPythonparserthatsupports errorrecoveryandround-tripparsingfordifferentPythonversions(in multiplePythonversions).Parsoisalsoabletolistmultiplesyntaxerrors inyourpythonfile. TableofContents ast—AbstractSyntaxTrees AbstractGrammar Nodeclasses Literals Variables Expressions Subscripting Comprehensions Statements Imports Controlflow Patternmatching Functionandclassdefinitions Asyncandawait astHelpers CompilerFlags Command-LineUsage Previoustopic PythonLanguageServices Nexttopic symtable—Accesstothecompiler’ssymboltables ThisPage ReportaBug ShowSource Navigation index modules| next| previous| Python» 3.10.4Documentation» ThePythonStandardLibrary» PythonLanguageServices» ast—AbstractSyntaxTrees | "



請為這篇文章評分?