新聞中心
ast —- 抽象語法樹
源代碼: Lib/ast.py

創(chuàng)新互聯(lián)建站是專業(yè)的淄博網(wǎng)站建設(shè)公司,淄博接單;提供成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行淄博網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
ast 模塊幫助 python 程序處理 Python 語法的抽象語法樹。抽象語法或許會(huì)隨著 Python 的更新發(fā)布而改變;該模塊能夠幫助理解當(dāng)前語法在編程層面的樣貌。
抽象語法樹可通過將 ast.PyCF_ONLY_AST 作為旗標(biāo)傳遞給 compile() 內(nèi)置函數(shù)來生成,或是使用此模塊中提供的 parse() 輔助函數(shù)。返回結(jié)果將是一個(gè)對(duì)象樹,,其中的類都繼承自 ast.AST。抽象語法樹可被內(nèi)置的 compile() 函數(shù)編譯為一個(gè) Python 代碼對(duì)象。
抽象文法
抽象文法目前定義如下
-- ASDL's 4 builtin types are:-- identifier, int, string, constantmodule Python{mod = Module(stmt* body, type_ignore* type_ignores)| Interactive(stmt* body)| Expression(expr body)| FunctionType(expr* argtypes, expr returns)stmt = FunctionDef(identifier name, arguments args,stmt* body, expr* decorator_list, expr? returns,string? type_comment)| AsyncFunctionDef(identifier name, arguments args,stmt* body, expr* decorator_list, expr? returns,string? type_comment)| ClassDef(identifier name,expr* bases,keyword* keywords,stmt* body,expr* decorator_list)| Return(expr? value)| Delete(expr* targets)| Assign(expr* targets, expr value, string? type_comment)| AugAssign(expr target, operator op, expr value)-- 'simple' indicates that we annotate simple name without parens| AnnAssign(expr target, expr annotation, expr? value, int simple)-- use 'orelse' because else is a keyword in target languages| For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)| AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)| While(expr test, stmt* body, stmt* orelse)| If(expr test, stmt* body, stmt* orelse)| With(withitem* items, stmt* body, string? type_comment)| AsyncWith(withitem* items, stmt* body, string? type_comment)| Match(expr subject, match_case* cases)| Raise(expr? exc, expr? cause)| Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)| TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)| Assert(expr test, expr? msg)| Import(alias* names)| ImportFrom(identifier? module, alias* names, int? level)| Global(identifier* names)| Nonlocal(identifier* names)| Expr(expr value)| Pass | Break | Continue-- col_offset is the byte offset in the utf8 string the parser usesattributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)-- BoolOp() can use left & right?expr = BoolOp(boolop op, expr* values)| NamedExpr(expr target, expr value)| BinOp(expr left, operator op, expr right)| UnaryOp(unaryop op, expr operand)| Lambda(arguments args, expr body)| IfExp(expr test, expr body, expr orelse)| Dict(expr* keys, expr* values)| Set(expr* elts)| ListComp(expr elt, comprehension* generators)| SetComp(expr elt, comprehension* generators)| DictComp(expr key, expr value, comprehension* generators)| GeneratorExp(expr elt, comprehension* generators)-- the grammar constrains where yield expressions can occur| Await(expr value)| Yield(expr? value)| YieldFrom(expr value)-- need sequences for compare to distinguish between-- x < 4 < 3 and (x < 4) < 3| Compare(expr left, cmpop* ops, expr* comparators)| Call(expr func, expr* args, keyword* keywords)| FormattedValue(expr value, int conversion, expr? format_spec)| JoinedStr(expr* values)| Constant(constant value, string? kind)-- the following expression can appear in assignment context| Attribute(expr value, identifier attr, expr_context ctx)| Subscript(expr value, expr slice, expr_context ctx)| Starred(expr value, expr_context ctx)| Name(identifier id, expr_context ctx)| List(expr* elts, expr_context ctx)| Tuple(expr* elts, expr_context ctx)-- can appear only in Subscript| Slice(expr? lower, expr? upper, expr? step)-- col_offset is the byte offset in the utf8 string the parser usesattributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)expr_context = Load | Store | Delboolop = And | Oroperator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift| RShift | BitOr | BitXor | BitAnd | FloorDivunaryop = Invert | Not | UAdd | USubcmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIncomprehension = (expr target, expr iter, expr* ifs, int is_async)excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)attributes (int lineno, int col_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 = (identifier arg, expr? annotation, string? type_comment)attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)-- keyword arguments supplied to call (NULL identifier for **kwargs)keyword = (identifier? arg, expr value)attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)-- import name with optional 'as' alias.alias = (identifier name, identifier? asname)attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)withitem = (expr context_expr, expr? optional_vars)match_case = (pattern pattern, expr? guard, stmt* body)pattern = MatchValue(expr value)| MatchSingleton(constant value)| MatchSequence(pattern* patterns)| MatchMapping(expr* keys, pattern* patterns, identifier? rest)| MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)| MatchStar(identifier? name)-- The optional "rest" MatchMapping parameter handles capturing extra mapping keys| MatchAs(pattern? pattern, identifier? name)| MatchOr(pattern* patterns)attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)type_ignore = TypeIgnore(int lineno, string tag)}
節(jié)點(diǎn)類
class ast.AST
This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl file, which is reproduced above. They are defined in the _ast C module and re-exported in ast.
抽象語法定義的每個(gè)左側(cè)符號(hào)(比方說, ast.stmt 或者 ast.expr)定義了一個(gè)類。另外,在抽象語法定義的右側(cè),對(duì)每一個(gè)構(gòu)造器也定義了一個(gè)類;這些類繼承自樹左側(cè)的類。比如,ast.BinOp 繼承自 ast.expr。對(duì)于多分支產(chǎn)生式(也就是”和規(guī)則”),樹右側(cè)的類是抽象的;只有特定構(gòu)造器結(jié)點(diǎn)的實(shí)例能被構(gòu)造。
_fields
每個(gè)具體類都有個(gè)屬性 _fields, 用來給出所有子節(jié)點(diǎn)的名字。
每個(gè)具體類的實(shí)例對(duì)它每個(gè)子節(jié)點(diǎn)都有一個(gè)屬性,對(duì)應(yīng)類型如文法中所定義。比如,ast.BinOp 的實(shí)例有個(gè)屬性
left,類型是ast.expr.如果這些屬性在文法中標(biāo)記為可選(使用問號(hào)),對(duì)應(yīng)值可能會(huì)是
None。如果這些屬性有零或多個(gè)(用星號(hào)標(biāo)記),對(duì)應(yīng)值會(huì)用Python的列表來表示。所有可能的屬性必須在用 compile() 編譯得到AST時(shí)給出,且是有效的值。lineno
col_offset
end_lineno
end_col_offset
ast.expr和ast.stmt子類的實(shí)例有 lineno、col_offset、end_lineno 和 end_lineno 屬性。lineno 和 end_lineno 是源代碼的第一行行數(shù)和最后一行行數(shù)(從1開始, 所以第一行行數(shù)是1),而 col_offset 和 end_col_offset 是該生成節(jié)點(diǎn)第一個(gè)和最后一個(gè) token 的 UTF-8 字節(jié)偏移量。記錄下 UTF-8 偏移量的原因是 parser 內(nèi)部使用 UTF-8 。注意編譯器不需要結(jié)束位置,所以結(jié)束位置是可選的。結(jié)束偏移在最后一個(gè)符號(hào)*之后*,例如你可以通過
source_line[node.col_offset : node.end_col_offset]獲得一個(gè)單行表達(dá)式節(jié)點(diǎn)的源碼片段。
一個(gè)類的構(gòu)造器 ast.T 像下面這樣parse它的參數(shù)。
如果有位置參數(shù),它們必須和
T._fields中的元素一樣多;他們會(huì)像這些名字的屬性一樣被賦值。如果有關(guān)鍵字參數(shù),它們必須被設(shè)為和給定值同名的屬性。
比方說,要?jiǎng)?chuàng)建和填充節(jié)點(diǎn) ast.UnaryOp,你得用
node = ast.UnaryOp()node.op = ast.USub()node.operand = ast.Constant()node.operand.value = 5node.operand.lineno = 0node.operand.col_offset = 0node.lineno = 0node.col_offset = 0
或者更緊湊點(diǎn)
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),lineno=0, col_offset=0)
在 3.8 版更改: 類 ast.Constant 現(xiàn)在用于所有常量。
在 3.9 版更改: 簡單索引由它們的值表示,擴(kuò)展切片表示為元組。
3.8 版后已移除: 舊的類 ast.Num、ast.Str、 ast.Bytes、ast.NameConstant 和 ast.Ellipsis 仍然有效,但是它們會(huì)在未來的 Python 版本中被移除。同時(shí),實(shí)例化它們會(huì)返回一個(gè)不同類的實(shí)例。
3.9 版后已移除: 舊的類 ast.Index 和 ast.ExtSlice 仍然有效,但是它們會(huì)在未來的 Python 版本中被移除。同時(shí),實(shí)例化它們會(huì)返回一個(gè)不同類的實(shí)例。
備注
在此顯示的特定節(jié)點(diǎn)類的描述最初是改編自杰出的 Green Tree Snakes 項(xiàng)目及其所有貢獻(xiàn)者。
字面值
class ast.Constant(value)
一個(gè)常量。 Constant 字面值的 value 屬性即為其代表的 Python 對(duì)象。它可以代表簡單的數(shù)字,字符串或者 None 對(duì)象,但是也可以代表所有元素都是常量的不可變?nèi)萜鳎ɡ缭M或凍結(jié)集合)。
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))Expression(body=Constant(value=123))
class ast.FormattedValue(value, conversion, format_spec)
節(jié)點(diǎn)是以一個(gè) f-字符串形式的格式化字段來代表的。 如果該字符串只包含單個(gè)格式化字段而沒有任何其他內(nèi)容則節(jié)點(diǎn)可以被隔離,否則它將在 JoinedStr 中出現(xiàn)。
value為任意的表達(dá)式節(jié)點(diǎn)(如一個(gè)字面值、變量或函數(shù)調(diào)用)。conversion是一個(gè)整數(shù):-1: 無格式化
115:
!s字符串格式化114:
!rrepr 格式化97:
!aascii 格式化
format_spec是一個(gè)代表值的格式化的 JoinedStr 節(jié)點(diǎn),或者如果未指定格式則為None。conversion和format_spec可以被同時(shí)設(shè)置。
class ast.JoinedStr(values)
一個(gè) f-字符串,由一系列 FormattedValue 和 Constant 節(jié)點(diǎn)組成。
>>> 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')]))]))
class ast.List(elts, ctx)
class ast.Tuple(elts, ctx)
一個(gè)列表或元組。 elts 保存一個(gè)代表元素的節(jié)點(diǎn)的列表。 ctx 在容器為賦值的目標(biāo)時(shí) (如 (x,y)=something) 是 Store,否則是 Load。
>>> 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()))
class ast.Set(elts)
一個(gè)集合。 elts 保存一個(gè)代表集合的元組的節(jié)點(diǎn)的列表。
>>> 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)]))
class ast.Dict(keys, values)
一個(gè)字典。 keys 和 values 保存分別代表鍵和值的節(jié)點(diǎn)的列表,按照匹配的順序(即當(dāng)調(diào)用 dictionary.keys() 和 dictionary.values() 時(shí)將返回的結(jié)果)。
當(dāng)使用字典字面值進(jìn)行字典解包操作時(shí)要擴(kuò)展的表達(dá)式放入 values 列表,并將 None 放入 keys 的對(duì)應(yīng)位置。
>>> 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())]))
變量
class ast.Name(id, ctx)
一個(gè)變量名。 id 將名稱保存為字符串,而 ctx 為下列類型之一。
class ast.Load
class ast.Store
class ast.Del
變量引用可被用來載入一個(gè)變量的值,為其賦一個(gè)新值,或是將其刪除。 變量引用會(huì)給出一個(gè)上下文來區(qū)分這幾種情況。
>>> 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('del a'), indent=4))Module(body=[Delete(targets=[Name(id='a', ctx=Del())])],type_ignores=[])
class ast.Starred(value, ctx)
一個(gè) *var 變量引用。 value 保存變量,通常為一個(gè) Name 節(jié)點(diǎn)。 此類型必須在構(gòu)建 Call 節(jié)點(diǎn)并傳入 *args 時(shí)被使用。
>>> 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=[])
表達(dá)式
class ast.Expr(value)
當(dāng)一個(gè)表達(dá)式,例如函數(shù)調(diào)用,本身作為一個(gè)語句出現(xiàn)并且其返回值未被使用或存儲(chǔ)時(shí),它會(huì)被包裝在此容器中。 value 保存本節(jié)中的其他節(jié)點(diǎn)之一,一個(gè) Constant, Name, Lambda, Yield 或者 YieldFrom 節(jié)點(diǎn)。
>>> print(ast.dump(ast.parse('-a'), indent=4))Module(body=[Expr(value=UnaryOp(op=USub(),operand=Name(id='a', ctx=Load())))],type_ignores=[])
class ast.UnaryOp(op, operand)
一個(gè)單目運(yùn)算。 op 是運(yùn)算符,而 operand 是任意表達(dá)式節(jié)點(diǎn)。
class ast.UAdd
class ast.USub
class ast.Not
class ast.Invert
單目運(yùn)算符對(duì)應(yīng)的形符。 Not 是 not 關(guān)鍵字,Invert 是 ~ 運(yùn)算符。
>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))Expression(body=UnaryOp(op=Not(),operand=Name(id='x', ctx=Load())))
class ast.BinOp(left, op, right)
一個(gè)雙目運(yùn)算(如相加或相減)。 op 是運(yùn)算符,而 left 和 right 是任意表達(dá)式節(jié)點(diǎn)。
>>> 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())))
class ast.Add
class ast.Sub
class ast.Mult
class ast.Div
class ast.FloorDiv
class ast.Mod
class ast.Pow
class ast.LShift
class ast.RShift
class ast.BitOr
class ast.BitXor
class ast.BitAnd
class ast.MatMult
雙目運(yùn)算符對(duì)應(yīng)的形符。
class ast.BoolOp(op, values)
一個(gè)布爾運(yùn)算,’or’ 或者 ‘a(chǎn)nd’。 op 是 Or 或者 And。 values 是參與運(yùn)算的值。 具有相同運(yùn)算符的連續(xù)運(yùn)算,如 a or b or c,會(huì)被折疊為具有多個(gè)值的單個(gè)節(jié)點(diǎn)。
這不包括 not,它屬于 UnaryOp。
>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))Expression(body=BoolOp(op=Or(),values=[Name(id='x', ctx=Load()),Name(id='y', ctx=Load())]))
class ast.And
class ast.Or
布爾運(yùn)算符對(duì)應(yīng)的形符。
class ast.Compare(left, ops, comparators)
兩個(gè)或更多值之間的比較運(yùn)算。 left 是參加比較的第一個(gè)值,ops 是由運(yùn)算符組成的列表,而 comparators 是由參加比較的第一個(gè)元素之后的值組成的列表。
>>> 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)]))
class ast.Eq
class ast.NotEq
class ast.Lt
class ast.LtE
class ast.Gt
class ast.GtE
class ast.Is
class ast.IsNot
class ast.In
class ast.NotIn
比較運(yùn)算符對(duì)應(yīng)的形符。
class ast.Call(func, args, keywords, starargs, kwargs)
一個(gè)函數(shù)調(diào)用。 func 是函數(shù),它通常是一個(gè) Name 或 Attribute 對(duì)象。 對(duì)于其參數(shù):
args保存由按位置傳入的參數(shù)組成的列表。keywords保存了一個(gè)代表以關(guān)鍵字傳入的參數(shù)的 keyword 對(duì)象的列表。
當(dāng)創(chuàng)建一個(gè) Call 節(jié)點(diǎn)時(shí),需要有 args 和 keywords,但它們可以為空列表。 starargs 和 kwargs 是可選的。
>>> 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()))]))
class ast.keyword(arg, value)
傳給函數(shù)調(diào)用或類定義的關(guān)鍵字參數(shù)。 arg 是形參名稱對(duì)應(yīng)的原始字符串,value 是要傳入的節(jié)點(diǎn)。
class ast.IfExp(test, body, orelse)
一個(gè)表達(dá)式例如 a if b else c。 每個(gè)字段保存一個(gè)單獨(dú)節(jié)點(diǎn),因而在下面的示例中,三個(gè)節(jié)點(diǎn)均為 Name 節(jié)點(diǎn)。
>>> print(ast.dump(ast.parse('a if b else c', 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())))
class ast.Attribute(value, attr, ctx)
屬性訪問,例如 d.keys。 value 是一個(gè)節(jié)點(diǎn),通常為 Name。 attr 是一個(gè)給出屬性名稱的純字符串,而 ctx 根據(jù)屬性操作的方式可以為 Load, Store 或 Del。
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))Expression(body=Attribute(value=Name(id='snake', ctx=Load()),attr='colour',ctx=Load()))
class ast.NamedExpr(target, value)
一個(gè)帶名稱的表達(dá)式。 此 AST 節(jié)點(diǎn)是由賦值表達(dá)式運(yùn)算符(或稱海象運(yùn)算符)產(chǎn)生的。 與第一個(gè)參數(shù)可以有多個(gè)節(jié)點(diǎn)的 Assign 節(jié)點(diǎn)不同,在此情況下
target和value都必須為單獨(dú)節(jié)點(diǎn)。
>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))Expression(body=NamedExpr(target=Name(id='x', ctx=Store()),value=Constant(value=4)))
抽取
class ast.Subscript(value, slice, ctx)
抽取操作,如 l[1]。 value 是被抽取的對(duì)象(通常為序列或映射)。 slice 是索引號(hào)、切片或鍵。 它可以是一個(gè)包含 Slice 的 Tuple。 ctx 根據(jù)抽取所執(zhí)行的操作可以為 Load, Store 或 Del。
>>> 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()))
class ast.Slice(lower, upper, step)
常規(guī)切片 (形式如 lower:upper 或 lower:upper:step)。 只能在 Subscript 的 slice 字段內(nèi)部出現(xiàn),可以是直接切片對(duì)象或是作為 Tuple 的元素。
>>> 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()))
推導(dǎo)式
class ast.ListComp(elt, generators)
class ast.SetComp(elt, generators)
class ast.GeneratorExp(elt, generators)
class ast.DictComp(key, value, generators)
列表和集合推導(dǎo)式、生成器表達(dá)式以及字典推導(dǎo)式。 elt (或 key 和 value) 是一個(gè)代表將針對(duì)每個(gè)條目被求值的部分的單獨(dú)節(jié)點(diǎn)。
generators 是一個(gè)由 comprehension 節(jié)點(diǎn)組成的列表。
>>> print(ast.dump(ast.parse('[x for x in numbers]', 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**2 for x in numbers}', 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('{x for x in numbers}', 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)]))
class ast.comprehension(target, iter, ifs, is_async)
推導(dǎo)式中的一個(gè) for 子句。 target 是針對(duì)每個(gè)元素使用的引用 —— 通常為一個(gè) Name 或 Tuple 節(jié)點(diǎn)。 iter 是要執(zhí)行迭代的對(duì)象。 ifs 是一個(gè)由測(cè)試表達(dá)式組成的列表:每個(gè) for 子句都可以擁有多個(gè) ifs。
is_async 表明推導(dǎo)式是異步的 (使用 async for 而不是 for)。 它的值是一個(gè)整數(shù) (0 或 1)。
>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),... indent=4)) # Multiple comprehensions in one.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**2 for n in it if n>5 if n<10)', mode='eval'),... indent=4)) # generator comprehensionExpression(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 名稱欄目:創(chuàng)新互聯(lián)Python教程:ast —- 抽象語法樹
本文鏈接:http://m.fisionsoft.com.cn/article/djhjoeo.html


咨詢
建站咨詢
