Source text — English
Translation — Bahasa Indonesia
:mod:`!ast` --- Abstract syntax trees
:mod:`!ast` --- Struktur pohon sintaksis abstrak
**Source code:** :source:`Lib/ast.py`
**Code sumber:** :source:`Lib/ast.py`
The :mod:`!ast` module helps Python applications to process trees of the Python abstract syntax grammar. The abstract syntax itself might change with each Python release; this module helps to find out programmatically what the current grammar looks like.
Modul :mod:`!ast` membantu aplikasi Python memproses pohon tata bahasa sintaksis abstrak Python. Sintaksis abstrak itu sendiri mungkin berubah pada setiap rilis Python; modul ini membantu mengetahui secara terprogram seperti apa tata bahasa saat ini.
An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as a flag to the :func:`compile` built-in function, or using the :func:`parse` helper provided in this module. The result will be a tree of objects whose classes all inherit from :class:`ast.AST`. An abstract syntax tree can be compiled into a Python code object using the built-in :func:`compile` function.
Sebuah pohon sintaksis abstrak dapat dihasilkan dengan meneruskan :data:`ast.PyCF_ONLY_AST` sebagai penanda A ke fungsi bawaan :func:`compile`, atau menggunakan fungsi pembantu :func:`parse` yang disediakan di modul ini. Hasilnya akan berupa pohon objek yang kelas-kelasnya semuanya mewarisi dari :class:`ast.AST`. Sebuah pohon sintaksis abstrak dapat dikompilasi menjadi objek kode Python menggunakan fungsi bawaan :func:`compile`.
Abstract grammar
Tata bahasa abstrak
The abstract grammar is currently defined as follows:
Tata bahasa abstrak saat ini didefinisikan sebagai berikut:
-- ASDL's 4 builtin types are:
-- identifier, int, string, constant
module 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, type_param* type_params)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment, type_param* type_params)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list,
type_param* type_params)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| TypeAlias(expr name, type_param* type_params, expr value)
| 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, int? is_lazy)
| ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (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)
| Interpolation(expr value, constant str, int conversion, expr? format_spec)
| JoinedStr(expr* values)
| TemplateStr(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 uses
attributes (int lineno, int col_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 = (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)
type_param = TypeVar(identifier name, expr? bound, expr? default_value)
| ParamSpec(identifier name, expr? default_value)
| TypeVarTuple(identifier name, expr? default_value)
attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}
-- 4 types bawaan ASDL adalah:
-- identifier, int, string, konstanta
module 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, type_param* type_params)
| AsyncFunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns,
string? type_comment, type_param* type_params)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
stmt* body,
expr* decorator_list,
type_param* type_params)
| Return(expr? value)
| Delete(expr* targets)
| Assign(expr* targets, expr value, string? type_comment)
| TypeAlias(expr name, type_param* type_params, expr value)
| AugAssign(expr target, operator op, expr value)
-- 'simple' menunjukkan bahwa kita menganotasi nama sederhana tanpa tanda kurung
| AnnAssign(expr target, expr annotation, expr? value, int simple)
-- gunakan 'orelse' karena else adalah kata kunci dalam bahasa target
| 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, int? is_lazy)
| ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)
| Global(identifier* names)
| Nonlocal(identifier* names)
| Expr(expr value)
| Pass | Break | Continue
-- col_offset adalah offset byte dalam string utf8 yang digunakan pengurai
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- BoolOp() dapat menggunakan 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)
-- gramatika membatasi di mana ekspresi yield dapat muncul
| Await(expr value)
| Yield(expr? value)
| YieldFrom(expr value)
-- memerlukan urutan untuk perbandingan guna membedakan antara
-- x < 4 < 3 dan (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)
| Interpolation(expr value, constant str, int conversion, expr? format_spec)
| JoinedStr(expr* values)
| TemplateStr(expr* values)
| Constant(constant value, string? kind)
-- ekspresi berikut dapat muncul dalam konteks penugasan
| 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)
-- hanya dapat muncul dalam Subscript
| Slice(expr? lower, expr? upper, expr? step)
-- col_offset adalah offset byte dalam string utf8 yang digunakan pengurai
attributes (int lineno, int col_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 = (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)
-- argumen kata kunci yang diberikan ke pemanggilan (identifier NULL untuk **kwargs)
keyword = (identifier? arg, expr value)
attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)
-- impor nama dengan alias 'as' yang opsional.
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)
type_param = TypeVar(identifier name, expr? bound, expr? default_value)
| ParamSpec(identifier name, expr? default_value)
| TypeVarTuple(identifier name, expr? default_value)
attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)
}
Node classes
classes node
This is the abstract base of all AST node classes. The actual node classes are derived from the :file:`Parser/Python.asdl` file, which is reproduced :ref:`above <abstract-grammar>`. They are defined in the :mod:`!_ast` C module and re-exported in :mod:`!ast`.
Ini adalah basis abstrak dari semua classes node AST. classes node yang sebenarnya berasal dari berkas :file:`Parser/Python.asdl`, yang ditampilkan ulang :ref:`di atas <abstract-grammar>`. Mereka didefinisikan di modul C :mod:`!_ast` dan diekspor ulang di :mod:`!ast`.
There is one class defined for each left-hand side symbol in the abstract grammar (for example, :class:`ast.stmt` or :class:`ast.expr`). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, :class:`ast.BinOp` inherits from :class:`ast.expr`. For production rules with alternatives (aka "sums"), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.
Ada satu kelas yang didefinisikan untuk setiap simbol sisi kiri dalam tata bahasa abstrak (Sebagai contoh, :class:`ast.stmt` atau :class:`ast.expr`). Selain itu, ada satu kelas yang didefinisikan untuk setiap pembangun, *Constructor* di sisi kanan; classes ini mewarisi dari classes untuk pohon sisi kiri. Sebagai contoh, :class:`ast.BinOp` mewarisi dari :class:`ast.expr`. Untuk aturan produksi dengan alternatif (alias "sums"), kelas sisi kiri bersifat abstrak: hanya instans node pembangun, *Constructor* tertentu yang akan dibuat.
Each concrete class has an attribute :attr:`!_fields` which gives the names of all child nodes.
Setiap kelas konkret memiliki atribut :attr:`!_fields` yang memberikan nama semua node anak.
Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, :class:`ast.BinOp` instances have an attribute :attr:`left` of type :class:`ast.expr`.
Setiap instans dari kelas konkret memiliki satu atribut untuk tiap node anak, dengan tipe seperti yang ditentukan dalam tata bahasa. Sebagai contoh, instans :class:`ast.BinOp` memiliki atribut :attr:`left` bertipe :class:`ast.expr`.
If these attributes are marked as optional in the grammar (using a question mark), the value might be ``None``. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with :func:`compile`.
Jika atribut-atribut ini ditandai sebagai opsional dalam tata bahasa (menggunakan tanda tanya), nilainya bisa ``None``. Jika atribut-atribut dapat memiliki nol-atau-lebih nilai (ditandai dengan tanda bintang), nilainya direpresentasikan sebagai list Python. Semua atribut yang memungkinkan harus ada dan memiliki nilai yang valid saat mengompilasi AST dengan :func:`compile`.
The :attr:`!_field_types` attribute on each concrete class is a dictionary mapping field names (as also listed in :attr:`_fields`) to their types.
Atribut :attr:`!_field_types` pada setiap kelas konkret adalah dictionary yang memetakan nama field (seperti juga tercantum di :attr:`_fields`) ke types mereka.
>>> ast.TypeVar._field_types
{'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None}
>>> ast.TypeVar._field_types
{'name': <class 'str'>, 'bound': ast.expr | None, 'default_value': ast.expr | None}
Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have :attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, and :attr:`end_col_offset` attributes. The :attr:`lineno` and :attr:`end_lineno` are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the :attr:`col_offset` and :attr:`end_col_offset` are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.
Instans dari subkelas :class:`ast.expr` dan :class:`ast.stmt` memiliki atribut :attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, dan :attr:`end_col_offset`. :attr:`lineno` dan :attr:`end_lineno` adalah nomor baris pertama dan terakhir dari rentang teks sumber (diindeks mulai 1 sehingga baris pertama adalah baris 1) dan :attr:`col_offset` serta :attr:`end_col_offset` adalah offset byte UTF-8 yang sesuai dari token pertama dan terakhir yang menghasilkan node tersebut. Offset UTF-8 dicatat karena parser menggunakan UTF-8 secara internal.
Note that the end positions are not required by the compiler and are therefore optional. The end offset is *after* the last symbol, for example one can get the source segment of a one-line expression node using ``source_line[node.col_offset : node.end_col_offset]``.
Perhatikan bahwa posisi akhir tidak diwajibkan oleh kompilator dan karenanya bersifat opsional. Offset akhir berada setelah simbol terakhir; sebagai contoh, Anda bisa mendapatkan segmen sumber dari node ekspresi satu baris menggunakan ``source_line[node.col_offset : node.end_col_offset]``.
The constructor of a class :class:`ast.T` parses its arguments as follows:
pembangun, *Constructor* untuk sebuah kelas :class:`ast.T` mengurai argumennya sebagai berikut:
If there are positional arguments, there must be as many as there are items in :attr:`T._fields`; they will be assigned as attributes of these names.
Jika ada argumen posisional, jumlahnya harus sama banyaknya dengan item di :attr:`T._fields`; item-item tersebut akan ditetapkan sebagai atribut dengan nama-nama tersebut.
If there are keyword arguments, they will set the attributes of the same names to the given values.
Jika ada argumen Kata Kunci *Keyword Arguments*, argumen tersebut akan men-set atribut dengan nama yang sama ke nilai yang diberikan.
For example, to create and populate an :class:`ast.UnaryOp` node, you could use ::
Sebagai contoh, untuk membuat dan mengisi sebuah node :class:`ast.UnaryOp`, Anda bisa gunakan ::
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
lineno=0, col_offset=0)
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),
lineno=0, col_offset=0)
If a field that is optional in the grammar is omitted from the constructor, it defaults to ``None``. If a list field is omitted, it defaults to the empty list. If a field of type :class:`!ast.expr_context` is omitted, it defaults to :class:`Load() <ast.Load>`. If any other field is omitted, a :exc:`DeprecationWarning` is raised and the AST node will not have this field. In Python 3.15, this condition will raise an error.
Jika sebuah field yang bersifat opsional dalam tata bahasa diabaikan dari pembangun, *Constructor*, nilainya menjadi bawaan ``None``. Jika sebuah field daftar diabaikan, nilainya menjadi list kosong. Jika sebuah field bertipe :class:`!ast.expr_context` diabaikan, nilainya menjadi :class:`Load() <ast.Load>`. Jika field lain diabaikan, sebuah :exc:`DeprecationWarning` akan muncul dan node AST tidak akan memiliki field tersebut. Di Python 3.15, kondisi ini akan memicu galat.
Class :class:`ast.Constant` is now used for all constants.
Kelas :class:`ast.Constant` sekarang digunakan untuk semua konstanta.
Simple indices are represented by their value, extended slices are represented as tuples.
Indeks sederhana direpresentasikan oleh nilainya, potongan yang diperluas direpresentasikan sebagai *Tuples*.
AST node constructors were changed to provide sensible defaults for omitted fields: optional fields now default to ``None``, list fields default to an empty list, and fields of type :class:`!ast.expr_context` default to :class:`Load() <ast.Load>`. Previously, omitted attributes would not exist on constructed nodes (accessing them raised :exc:`AttributeError`).
pembangun node AST telah diubah untuk menyediakan nilai bawaan yang masuk akal bagi field yang diabaikan: field opsional kini bawaannya ``None``, field daftar bawaannya list kosong, dan field bertipe :class:`!ast.expr_context` bawaannya :class:`Load() <ast.Load>`. Sebelumnya, atribut yang diabaikan tidak akan ada pada node yang dibangun (mengaksesnya menimbulkan :exc:`AttributeError`).
The :meth:`~object.__repr__` output of :class:`~ast.AST` nodes includes the values of the node fields.
Keluaran :meth:`~object.__repr__` dari node :class:`~ast.AST` menyertakan nilai dari field node.
Previous versions of Python provided the AST classes :class:`!ast.Num`, :class:`!ast.Str`, :class:`!ast.Bytes`, :class:`!ast.NameConstant` and :class:`!ast.Ellipsis`, which were deprecated in Python 3.8. These classes were removed in Python 3.14, and their functionality has been replaced with :class:`ast.Constant`.
Versi Python sebelumnya menyediakan classes AST :class:`!ast.Num`, :class:`!ast.Str`, :class:`!ast.Bytes`, :class:`!ast.NameConstant` dan :class:`!ast.Ellipsis`, yang menjadi usang di Python 3.8. classes ini dihapus di Python 3.14, dan fungsionalitasnya telah digantikan dengan :class:`ast.Constant`.
Old classes :class:`!ast.Index` and :class:`!ast.ExtSlice` are still available, but they will be removed in future Python releases. In the meantime, instantiating them will return an instance of a different class.
classes Lama *Old* :class:`!ast.Index` dan :class:`!ast.ExtSlice` masih tersedia, tapi akan dihapus pada rilis Python mendatang. Sementara itu, menginstansiasi mereka akan mengembalikan instans dari kelas yang berbeda.
Previous versions of Python allowed the creation of AST nodes that were missing required fields. Similarly, AST node constructors allowed arbitrary keyword arguments that were set as attributes of the AST node, even if they did not match any of the fields of the AST node. These cases now raise a :exc:`TypeError`.
Versi Python sebelumnya mengizinkan pembuatan node AST yang kekurangan field yang wajib. Demikian pula, pembangun, *Constructor* node AST mengizinkan argumen Kata Kunci *Keyword Arguments* sembarang yang di-set sebagai atribut dari node AST, bahkan jika argumen tersebut tidak cocok dengan field mana pun dari node AST. Kasus-kasus ini sekarang menimbulkan :exc:`TypeError`.
In the :ref:`grammar above <abstract-grammar>`, the AST node classes that correspond to production rules with variants (aka "sums") are abstract classes. Previous versions of Python allowed for the creation of direct instances of these abstract node classes. This behavior is deprecated and will be removed in Python 3.20.
Dalam :ref:`tata bahasa di atas <abstract-grammar>`, classes node AST yang sesuai dengan aturan produksi dengan varian (alias "sums") adalah classes abstrak. Versi Python sebelumnya mengizinkan pembuatan instans langsung dari classes node abstrak ini. Perilaku ini usang dan akan dihapus di Python 3.20.
The descriptions of the specific node classes displayed here were initially adapted from the fantastic `Green Tree Snakes <https://greentreesnakes.readthedocs.io/en/latest/>`__ project and all its contributors.
Deskripsi classes node spesifik yang ditampilkan di sini awalnya diadaptasi dari proyek hebat `Green Tree Snakes <https://greentreesnakes.readthedocs.io/en/latest/>`__ dan semua kontributornya.
Root nodes
Node akar
A Python module, as with :ref:`file input <file-input>`. Node type generated by :func:`ast.parse` in the default ``"exec"`` *mode*.
Sebuah modul Python, seperti pada :ref:`masukan dari berkas <file-input>`. Tipe node yang dihasilkan oleh :func:`ast.parse` dalam *mode* bawaan ``"exec"``.
``body`` is a :class:`list` of the module's :ref:`ast-statements`.
``body`` adalah :class:`list` dari :ref:`ast-statements` milik modul.
``type_ignores`` is a :class:`list` of the module's type ignore comments; see :func:`ast.parse` for more details.
``type_ignores`` adalah :class:`list` dari komentar pengabaian tipe milik modul; lihat :func:`ast.parse` untuk detail lebih lanjut.
>>> print(ast.dump(ast.parse('x = 1'), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1))])
>>> print(ast.dump(ast.parse('x = 1'), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1))])
A single Python :ref:`expression input <expression-input>`. Node type generated by :func:`ast.parse` when *mode* is ``"eval"``.
Sebuah :ref:`masukan ekspresi <expression-input>` Python tunggal. Tipe node yang dihasilkan oleh :func:`ast.parse` ketika *mode* adalah ``"eval"``.
``body`` is a single node, one of the :ref:`expression types <ast-expressions>`.
``body`` adalah satu node, salah satu dari :ref:`types ekspresi <ast-expressions>`.
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
body=Constant(value=123))
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
body=Constant(value=123))
A single :ref:`interactive input <interactive>`, like in :ref:`tut-interac`. Node type generated by :func:`ast.parse` when *mode* is ``"single"``.
Sebuah :ref:`masukan interaktif <interactive>` tunggal, seperti di :ref:`tut-interac`. Tipe node yang dihasilkan oleh :func:`ast.parse` ketika *mode* adalah ``"single"``.
``body`` is a :class:`list` of :ref:`statement nodes <ast-statements>`.
``body`` adalah :class:`list` dari :ref:`node pernyataan <ast-statements>`.
>>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))
Interactive(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1)),
Assign(
targets=[
Name(id='y', ctx=Store())],
value=Constant(value=2))])
>>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))
Interactive(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1)),
Assign(
targets=[
Name(id='y', ctx=Store())],
value=Constant(value=2))])
A representation of an old-style type comments for functions, as Python versions prior to 3.5 didn't support :pep:`484` annotations. Node type generated by :func:`ast.parse` when *mode* is ``"func_type"``.
Representasi komentar tipe gaya lama untuk fungsi, karena Python versi sebelum 3.5 tidak mendukung anotasi :pep:`484`. Tipe node yang dihasilkan oleh :func:`ast.parse` ketika *mode* adalah ``"func_type"``.
Such type comments would look like this::
Komentar tipe seperti itu akan terlihat seperti ini::
def sum_two_number(a, b):
# type: (int, int) -> int
return a + b
def sum_two_number(a, b):
# type: (int, int) -> int
return a + b
``argtypes`` is a :class:`list` of :ref:`expression nodes <ast-expressions>`.
``argtypes`` adalah :class:`list` dari :ref:`node ekspresi <ast-expressions>`.
``returns`` is a single :ref:`expression node <ast-expressions>`.
``returns`` adalah sebuah :ref:`node ekspresi <ast-expressions>` tunggal.
>>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))
FunctionType(
argtypes=[
Name(id='int'),
Name(id='str')],
returns=Subscript(
value=Name(id='List'),
slice=Name(id='int')))
>>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))
FunctionType(
argtypes=[
Name(id='int'),
Name(id='str')],
returns=Subscript(
value=Name(id='List'),
slice=Name(id='int')))
Literals
Literal
A constant value. The ``value`` attribute of the ``Constant`` literal contains the Python object it represents. The values represented can be instances of :class:`str`, :class:`bytes`, :class:`int`, :class:`float`, :class:`complex`, and :class:`bool`, and the constants :data:`None` and :data:`Ellipsis`.
Sebuah nilai konstanta. Atribut ``value`` dari literal ``Constant`` memuat objek Python yang diwakilinya. Nilai yang direpresentasikan dapat berupa instance dari :class:`str`, :class:`bytes`, :class:`int`, :class:`float`, :class:`complex`, dan :class:`bool`, serta konstanta :data:`None` dan :data:`Ellipsis`.
The ``kind`` attribute is an optional string. For string literals with a ``u`` prefix, ``kind`` is set to ``'u'``. For all other constants, ``kind`` is ``None``.
Atribut ``kind`` adalah string opsional. Untuk literal string dengan awalan ``u``, ``kind`` di-set ke ``'u'``. Untuk semua konstanta lainnya, ``kind`` adalah ``None``.
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
body=Constant(value=123))
>>> print(ast.dump(ast.parse("u'hello'", mode='eval'), indent=4))
Expression(
body=Constant(value='hello', kind='u'))
>>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))
Expression(
body=Constant(value=123))
>>> print(ast.dump(ast.parse("u'hello'", mode='eval'), indent=4))
Expression(
body=Constant(value='hello', kind='u'))
Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in :class:`JoinedStr`.
Node yang merepresentasikan satu field pemformatan dalam sebuah f-string. Jika string berisi satu field pemformatan dan tidak ada yang lain, node ini dapat berdiri sendiri; jika tidak, ia muncul di :class:`JoinedStr`.
``value`` is any expression node (such as a literal, a variable, or a function call).
``value`` adalah node ekspresi apa pun (seperti literal, variabel, atau pemanggilan fungsi).
``conversion`` is an integer:
``conversion`` adalah bilangan bulat:
-1: no formatting
-1: tanpa pemformatan
97 (``ord('a')``): ``!a`` :func:`ASCII <ascii>` formatting
97 (``ord('a')``): ``!a`` pemformatan :func:`ASCII <ascii>`
114 (``ord('r')``): ``!r`` :func:`repr` formatting
114 (``ord('r')``): ``!r`` pemformatan :func:`repr`
115 (``ord('s')``): ``!s`` :func:`string <str>` formatting
115 (``ord('s')``): ``!s`` pemformatan :func:`string <str>`
``format_spec`` is a :class:`JoinedStr` node representing the formatting of the value, or ``None`` if no format was specified. Both ``conversion`` and ``format_spec`` can be set at the same time.
``format_spec`` adalah node :class:`JoinedStr` yang merepresentasikan pemformatan nilai, atau ``None`` jika tidak ada format yang ditentukan. Baik ``conversion`` maupun ``format_spec`` dapat di-set secara bersamaan.
An f-string, comprising a series of :class:`FormattedValue` and :class:`Constant` nodes.
Sebuah f-string, terdiri dari serangkaian node :class:`FormattedValue` dan :class:`Constant`.
>>> 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'),
conversion=-1),
Constant(value=') is '),
FormattedValue(
value=Call(
func=Name(id='sin'),
args=[
Name(id='a')]),
conversion=-1,
format_spec=JoinedStr(
values=[
Constant(value='.3')]))]))
>>> 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'),
conversion=-1),
Constant(value=') is '),
FormattedValue(
value=Call(
func=Name(id='sin'),
args=[
Name(id='a')]),
conversion=-1,
format_spec=JoinedStr(
values=[
Constant(value='.3')]))]))
Node representing a template string literal, comprising a series of :class:`Interpolation` and :class:`Constant` nodes. These nodes may be any order, and do not need to be interleaved.
Node yang merepresentasikan literal string templat, terdiri dari serangkaian node :class:`Interpolation` dan :class:`Constant`. Node-node ini bisa dalam urutan apa pun, dan tidak perlu diselingi.
>>> expr = ast.parse('t"{name} finished {place:ordinal}"', mode='eval')
>>> print(ast.dump(expr, indent=4))
Expression(
body=TemplateStr(
values=[
Interpolation(
value=Name(id='name'),
str='name',
conversion=-1),
Constant(value=' finished '),
Interpolation(
value=Name(id='place'),
str='place',
conversion=-1,
format_spec=JoinedStr(
values=[
Constant(value='ordinal')]))]))
>>> expr = ast.parse('t"{name} finished {place:ordinal}"', mode='eval')
>>> print(ast.dump(expr, indent=4))
Expression(
body=TemplateStr(
values=[
Interpolation(
value=Name(id='name'),
str='name',
conversion=-1),
Constant(value=' finished '),
Interpolation(
value=Name(id='place'),
str='place',
conversion=-1,
format_spec=JoinedStr(
values=[
Constant(value='ordinal')]))]))
Node representing a single interpolation field in a template string literal.
Node yang merepresentasikan satu field interpolasi dalam literal string templat.
``value`` is any expression node (such as a literal, a variable, or a function call). This has the same meaning as ``FormattedValue.value``.
``value`` adalah node ekspresi apa pun (seperti literal, variabel, atau pemanggilan fungsi). Ini memiliki artinya yang sama seperti ``FormattedValue.value``.
``str`` is a constant containing the text of the interpolation expression.
``str`` adalah sebuah konstanta yang memuat teks dari ekspresi interpolasi.
If ``str`` is set to ``None``, then ``value`` is used to generate code when calling :func:`ast.unparse`. This no longer guarantees that the generated code is identical to the original and is intended for code generation.
Jika ``str`` di-set ke ``None``, maka ``value`` digunakan untuk menghasilkan code saat memanggil :func:`ast.unparse`. Ini tidak lagi menjamin bahwa code yang dihasilkan identik dengan aslinya dan dimaksudkan untuk pembuatan code.
-1: no conversion
-1: tidak ada konversi
97 (``ord('a')``): ``!a`` :func:`ASCII <ascii>` conversion
97 (``ord('a')``): ``!a`` konversi :func:`ASCII <ascii>`
114 (``ord('r')``): ``!r`` :func:`repr` conversion
114 (``ord('r')``): ``!r`` konversi :func:`repr`
115 (``ord('s')``): ``!s`` :func:`string <str>` conversion
115 (``ord('s')``): ``!s`` konversi :func:`string <str>`
This has the same meaning as ``FormattedValue.conversion``.
Ini memiliki artinya yang sama seperti ``FormattedValue.conversion``.
``format_spec`` is a :class:`JoinedStr` node representing the formatting of the value, or ``None`` if no format was specified. Both ``conversion`` and ``format_spec`` can be set at the same time. This has the same meaning as ``FormattedValue.format_spec``.
``format_spec`` adalah node :class:`JoinedStr` yang merepresentasikan pemformatan nilai, atau ``None`` jika tidak ada format yang ditentukan. Baik ``conversion`` maupun ``format_spec`` dapat di-set secara bersamaan. Ini memiliki artinya yang sama seperti ``FormattedValue.format_spec``.
A list or tuple. ``elts`` holds a list of nodes representing the elements. ``ctx`` is :class:`Store` if the container is an assignment target (i.e. ``(x,y)=something``), and :class:`Load` otherwise.
Sebuah list atau tupel. ``elts`` menampung list node yang merepresentasikan elemen. ``ctx`` adalah :class:`Store` jika kontainer merupakan target penugasan (mis. ``(x,y)=something``), dan :class:`Load` selain itu.
>>> 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)]))
>>> 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)]))
>>> 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)]))
>>> 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)]))
A set. ``elts`` holds a list of nodes representing the set's elements.
Sebuah set. ``elts`` menampung list node yang merepresentasikan elemen set.
>>> 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)]))
>>> 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)]))
A dictionary. ``keys`` and ``values`` hold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when calling :code:`dictionary.keys()` and :code:`dictionary.values()`).
Sebuah dictionary. ``keys`` dan ``values`` menampung list node yang merepresentasikan key dan nilainya masing-masing, dalam urutan yang sesuai (apa yang akan dikembalikan saat memanggil :code:`dictionary.keys()` dan :code:`dictionary.values()`).
When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the ``values`` list, with a ``None`` at the corresponding position in ``keys``.
Saat melakukan unpacking dictionary menggunakan literal dictionary, ekspresi yang akan diekspansi ditempatkan pada list ``values``, dengan ``None`` pada posisi yang bersesuaian di ``keys``.
>>> 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')]))
>>> 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')]))
Variables
Variabel
A variable name. ``id`` holds the name as a string, and ``ctx`` is one of the following types.
Nama variabel. ``id`` menyimpan nama sebagai sebuah string, dan ``ctx`` merupakan salah satu dari types berikut.
Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.
Referensi variabel dapat digunakan untuk memuat nilai variabel, menetapkan nilai baru padanya, atau menghapusnya. Referensi variabel diberi sebuah konteks untuk membedakan kasus-kasus ini.
>>> print(ast.dump(ast.parse('a'), indent=4))
Module(
body=[
Expr(
value=Name(id='a'))])
>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='a', ctx=Store())],
value=Constant(value=1))])
>>> print(ast.dump(ast.parse('del a'), indent=4))
Module(
body=[
Delete(
targets=[
Name(id='a', ctx=Del())])])
>>> print(ast.dump(ast.parse('a'), indent=4))
Module(
body=[
Expr(
value=Name(id='a'))])
>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='a', ctx=Store())],
value=Constant(value=1))])
>>> print(ast.dump(ast.parse('del a'), indent=4))
Module(
body=[
Delete(
targets=[
Name(id='a', ctx=Del())])])
A ``*var`` variable reference. ``value`` holds the variable, typically a :class:`Name` node. This type must be used when building a :class:`Call` node with ``*args``.
Sebuah referensi variabel ``*var``. ``value`` menyimpan variabel, biasanya berupa node :class:`Name`. Tipe ini harus digunakan saat membangun node :class:`Call` dengan ``*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'))])
>>> 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'))])
Expressions
Ekspresi
When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container. ``value`` holds one of the other nodes in this section, a :class:`Constant`, a :class:`Name`, a :class:`Lambda`, a :class:`Yield` or :class:`YieldFrom` node.
Ketika sebuah ekspresi, seperti pemanggilan fungsi, muncul sebagai pernyataan tersendiri dengan nilai kembalian yang tidak digunakan atau disimpan, ekspresi tersebut dibungkus dalam kontainer ini. ``value`` menyimpan salah satu node lain di bagian ini, yaitu node :class:`Constant`, :class:`Name`, :class:`Lambda`, :class:`Yield` atau :class:`YieldFrom`.
>>> print(ast.dump(ast.parse('-a'), indent=4))
Module(
body=[
Expr(
value=UnaryOp(
op=USub(),
operand=Name(id='a')))])
>>> print(ast.dump(ast.parse('-a'), indent=4))
Module(
body=[
Expr(
value=UnaryOp(
op=USub(),
operand=Name(id='a'))])
A unary operation. ``op`` is the operator, and ``operand`` any expression node.
Sebuah operasi unari. ``op`` adalah operator, dan ``operand`` adalah node ekspresi apa pun.
Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert` is the ``~`` operator.
Token operator unari. :class:`Not` adalah kata kunci ``not``, :class:`Invert` adalah operator ``~``.
>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
body=UnaryOp(
op=Not(),
operand=Name(id='x')))
>>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
body=UnaryOp(
op=Not(),
operand=Name(id='x')))
A binary operation (like addition or division). ``op`` is the operator, and ``left`` and ``right`` are any expression nodes.
Sebuah operasi biner (seperti penjumlahan atau pembagian). ``op`` adalah operator, dan ``left`` dan ``right`` adalah node ekspresi apa pun.
>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
body=BinOp(
left=Name(id='x'),
op=Add(),
right=Name(id='y')))
>>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))
Expression(
body=BinOp(
left=Name(id='x'),
op=Add(),
right=Name(id='y')))
Binary operator tokens.
Token operator biner.
A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`. ``values`` are the values involved. Consecutive operations with the same operator, such as ``a or b or c``, are collapsed into one node with several values.
Sebuah operasi boolean, 'or' atau 'and'. ``op`` adalah :class:`Or` atau :class:`And`. ``values`` adalah nilai-nilai yang terlibat. Operasi berurutan dengan operator yang sama, seperti ``a or b or c``, digabungkan menjadi satu node dengan beberapa nilai.
This doesn't include ``not``, which is a :class:`UnaryOp`.
Ini tidak mencakup ``not``, yang merupakan :class:`UnaryOp`.
>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
Expression(
body=BoolOp(
op=Or(),
values=[
Name(id='x'),
Name(id='y')]))
>>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))
Expression(
body=BoolOp(
op=Or(),
values=[
Name(id='x'),
Name(id='y')]))
Boolean operator tokens.
Token operator boolean.
A comparison of two or more values. ``left`` is the first value in the comparison, ``ops`` the list of operators, and ``comparators`` the list of values after the first element in the comparison.
Sebuah perbandingan dari dua atau lebih nilai. ``left`` adalah nilai pertama dalam perbandingan, ``ops`` adalah list operator, dan ``comparators`` adalah list nilai setelah elemen pertama dalam perbandingan.
>>> 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'),
Constant(value=10)]))
>>> 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'),
Constant(value=10)]))
Comparison operator tokens.
Token operator perbandingan.
A function call. ``func`` is the function, which will often be a :class:`Name` or :class:`Attribute` object. Of the arguments:
Panggilan fungsi. ``func`` adalah fungsinya, yang sering kali berupa objek :class:`Name` atau :class:`Attribute`. Mengenai argumen:
``args`` holds a list of the arguments passed by position.
``args`` menyimpan list argumen yang diteruskan berdasarkan posisi.
``keywords`` holds a list of :class:`.keyword` objects representing arguments passed by keyword.
``keywords`` menyimpan list objek :class:`.keyword` yang merepresentasikan argumen yang diteruskan berdasarkan keyword.
The ``args`` and ``keywords`` arguments are optional and default to empty lists.
Argumen ``args`` dan ``keywords`` bersifat opsional dan bawaannya adalah list kosong.
>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
body=Call(
func=Name(id='func'),
args=[
Name(id='a'),
Starred(
value=Name(id='d'))],
keywords=[
keyword(
arg='b',
value=Name(id='c')),
keyword(
value=Name(id='e'))]))
>>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))
Expression(
body=Call(
func=Name(id='func'),
args=[
Name(id='a'),
Starred(
value=Name(id='d'))],
keywords=[
keyword(
arg='b',
value=Name(id='c')),
keyword(
value=Name(id='e'))]))
A keyword argument to a function call or class definition. ``arg`` is a raw string of the parameter name, ``value`` is a node to pass in.
Sebuah argumen kata kunci untuk pemanggilan fungsi atau definisi kelas. ``arg`` adalah string mentah dari nama parameter, ``value`` adalah sebuah node yang akan diteruskan.
An expression such as ``a if b else c``. Each field holds a single node, so in the following example, all three are :class:`Name` nodes.
Sebuah ekspresi seperti ``a if b else c``. Setiap field menampung satu node, jadi pada contoh berikut, ketiganya adalah node :class:`Name`.
>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
body=IfExp(
test=Name(id='b'),
body=Name(id='a'),
orelse=Name(id='c')))
>>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))
Expression(
body=IfExp(
test=Name(id='b'),
body=Name(id='a'),
orelse=Name(id='c')))
Attribute access, e.g. ``d.keys``. ``value`` is a node, typically a :class:`Name`. ``attr`` is a bare string giving the name of the attribute, and ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to how the attribute is acted on.
Akses atribut, mis. ``d.keys``. ``value`` adalah sebuah node, biasanya :class:`Name`. ``attr`` adalah string polos yang menyatakan nama atribut, dan ``ctx`` adalah :class:`Load`, :class:`Store` atau :class:`Del` sesuai dengan bagaimana atribut tersebut dioperasikan.
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
body=Attribute(
value=Name(id='snake'),
attr='colour'))
>>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))
Expression(
body=Attribute(
value=Name(id='snake'),
attr='colour'))
A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the :class:`Assign` node in which the first argument can be multiple nodes, in this case both ``target`` and ``value`` must be single nodes.
Sebuah ekspresi bernama. Node AST ini dihasilkan oleh operator ekspresi Pemberian Nilai (juga dikenal sebagai operator walrus). Berbeda dengan node :class:`Assign` di mana argumen pertama bisa terdiri dari beberapa node, dalam kasus ini ``target`` dan ``value`` keduanya harus berupa satu node.
>>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))
Expression(
body=NamedExpr(
target=Name(id='x', ctx=Store()),
value=Constant(value=4)))
>>> 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
Pengindeksan
A subscript, such as ``l[1]``. ``value`` is the subscripted object (usually sequence or mapping). ``slice`` is an index, slice or key. It can be a :class:`Tuple` and contain a :class:`Slice`. ``ctx`` is :class:`Load`, :class:`Store` or :class:`Del` according to the action performed with the subscript.
Sebuah subskrip, seperti ``l[1]``. ``value`` adalah objek yang disubskrip (biasanya urutan atau pemetaan). ``slice`` adalah sebuah indeks, irisan, atau *Key*. Ini bisa berupa :class:`Tuple` dan berisi :class:`Slice`. ``ctx`` adalah :class:`Load`, :class:`Store` atau :class:`Del` sesuai dengan aksi yang dilakukan dengan subskrip tersebut.
>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
body=Subscript(
value=Name(id='l'),
slice=Tuple(
elts=[
Slice(
lower=Constant(value=1),
upper=Constant(value=2)),
Constant(value=3)])))
>>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
body=Subscript(
value=Name(id='l'),
slice=Tuple(
elts=[
Slice(
lower=Constant(value=1),
upper=Constant(value=2)),
Constant(value=3)])))
Regular slicing (on the form ``lower:upper`` or ``lower:upper:step``). Can occur only inside the *slice* field of :class:`Subscript`, either directly or as an element of :class:`Tuple`.
Pengirisan biasa (dalam bentuk ``lower:upper`` atau ``lower:upper:step``). Hanya dapat muncul di dalam field ``slice`` dari :class:`Subscript`, baik secara langsung maupun sebagai elemen dari :class:`Tuple`.
>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
body=Subscript(
value=Name(id='l'),
slice=Slice(
lower=Constant(value=1),
upper=Constant(value=2))))
>>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
body=Subscript(
value=Name(id='l'),
slice=Slice(
lower=Constant(value=1),
upper=Constant(value=2))))
Comprehensions
Komprehensi
List and set comprehensions, generator expressions, and dictionary comprehensions. ``elt`` (or ``key`` and ``value``) is a single node representing the part that will be evaluated for each item.
Komprehensi list dan set, ekspresi Pembangkit *Generator*, dan komprehensi dictionary. ``elt`` (atau ``key`` dan ``value``) adalah satu node yang merepresentasikan bagian yang akan dievaluasi untuk setiap item.
For dictionary comprehensions using unpacking, for example ``{**item for item in items}``, the expression to be expanded goes in ``key`` and ``value`` is ``None``.
Untuk komprehensi dictionary yang menggunakan unpacking, Sebagai contoh ``{**item for item in items}``, ekspresi yang akan diperluas ditempatkan di ``key`` dan ``value`` bernilai None.
``generators`` is a list of :class:`comprehension` nodes.
``generators`` adalah list dari node :class:`comprehension`.
>>> print(ast.dump(
... ast.parse('[x for x in numbers]', mode='eval'),
... indent=4,
... ))
Expression(
body=ListComp(
elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
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'),
value=BinOp(
left=Name(id='x'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
is_async=0)]))
>>> print(ast.dump(
... ast.parse('{x for x in numbers}', mode='eval'),
... indent=4,
... ))
Expression(
body=SetComp(
elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
is_async=0)]))
>>> print(ast.dump(
... ast.parse('[x for x in numbers]', mode='eval'),
... indent=4,
... ))
Expression(
body=ListComp(
elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
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'),
value=BinOp(
left=Name(id='x'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
is_async=0)]))
>>> print(ast.dump(
... ast.parse('{x for x in numbers}', mode='eval'),
... indent=4,
... ))
Expression(
body=SetComp(
elt=Name(id='x'),
generators=[
comprehension(
target=Name(id='x', ctx=Store()),
iter=Name(id='numbers'),
is_async=0)]))
One ``for`` clause in a comprehension. ``target`` is the reference to use for each element - typically a :class:`Name` or :class:`Tuple` node. ``iter`` is the object to iterate over. ``ifs`` is a list of test expressions: each ``for`` clause can have multiple ``ifs``.
Satu klausa ``for`` dalam sebuah komprehensi. ``target`` adalah referensi yang digunakan untuk setiap elemen - biasanya node :class:`Name` atau :class:`Tuple`. ``iter`` adalah objek yang akan diiterasi. ``ifs`` adalah list ekspresi pengujian: setiap klausa ``for`` dapat memiliki beberapa ``ifs``.
``is_async`` indicates a comprehension is asynchronous (using an ``async for`` instead of ``for``). The value is an integer (0 or 1).
``is_async`` menunjukkan bahwa sebuah komprehensi bersifat asinkron (menggunakan ``async for`` alih-alih ``for``). Nilainya adalah bilangan bulat (0 atau 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'),
args=[
Name(id='c')]),
generators=[
comprehension(
target=Name(id='line', ctx=Store()),
iter=Name(id='file'),
is_async=0),
comprehension(
target=Name(id='c', ctx=Store()),
iter=Name(id='line'),
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 comprehension
Expression(
body=GeneratorExp(
elt=BinOp(
left=Name(id='n'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='n', ctx=Store()),
iter=Name(id='it'),
ifs=[
Compare(
left=Name(id='n'),
ops=[
Gt()],
comparators=[
Constant(value=5)]),
Compare(
left=Name(id='n'),
ops=[
Lt()],
comparators=[
Constant(value=10)])],
is_async=0)]))
>>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
... indent=4)) # Async comprehension
Expression(
body=ListComp(
elt=Name(id='i'),
generators=[
comprehension(
target=Name(id='i', ctx=Store()),
iter=Name(id='soc'),
is_async=1)]))
>>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),
... indent=4)) # Beberapa komprehensi dalam satu.
Expression(
body=ListComp(
elt=Call(
func=Name(id='ord'),
args=[
Name(id='c')]),
generators=[
comprehension(
target=Name(id='line', ctx=Store()),
iter=Name(id='file'),
is_async=0),
comprehension(
target=Name(id='c', ctx=Store()),
iter=Name(id='line'),
is_async=0)]))
>>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),
... indent=4)) # komprehensi pembangkit
Expression(
body=GeneratorExp(
elt=BinOp(
left=Name(id='n'),
op=Pow(),
right=Constant(value=2)),
generators=[
comprehension(
target=Name(id='n', ctx=Store()),
iter=Name(id='it'),
ifs=[
Compare(
left=Name(id='n'),
ops=[
Gt()],
comparators=[
Constant(value=5)]),
Compare(
left=Name(id='n'),
ops=[
Lt()],
comparators=[
Constant(value=10)])],
is_async=0)]))
>>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),
... indent=4)) # komprehensi asinkron
Expression(
body=ListComp(
elt=Name(id='i'),
generators=[
comprehension(
target=Name(id='i', ctx=Store()),
iter=Name(id='soc'),
is_async=1)]))
Statements
Pernyataan
An assignment. ``targets`` is a list of nodes, and ``value`` is a single node.
Sebuah penugasan. ``targets`` adalah list node, dan ``value`` adalah satu node.
Multiple nodes in ``targets`` represents assigning the same value to each. Unpacking is represented by putting a :class:`Tuple` or :class:`List` within ``targets``.
Beberapa node dalam ``targets`` merepresentasikan penetapan nilai yang sama untuk masing-masing. Pembongkaran direpresentasikan dengan menempatkan :class:`Tuple` atau :class:`List` di dalam ``targets``.
``type_comment`` is an optional string with the type annotation as a comment.
``type_comment`` adalah string opsional dengan anotasi tipe sebagai komentarz.
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment
Module(
body=[
Assign(
targets=[
Name(id='a', ctx=Store()),
Name(id='b', ctx=Store())],
value=Constant(value=1))])
>>> 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'))])
>>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Penugasan ganda
Module(
body=[
Assign(
targets=[
Name(id='a', ctx=Store()),
Name(id='b', ctx=Store())],
value=Constant(value=1))])
>>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Pembongkaran
Module(
body=[
Assign(
targets=[
Tuple(
elts=[
Name(id='a', ctx=Store()),
Name(id='b', ctx=Store())],
ctx=Store())],
value=Name(id='c'))])
An assignment with a type annotation. ``target`` is a single node and can be a :class:`Name`, an :class:`Attribute` or a :class:`Subscript`. ``annotation`` is the annotation, such as a :class:`Constant` or :class:`Name` node. ``value`` is a single optional node.
Sebuah penugasan dengan anotasi tipe. ``target`` adalah satu node dan dapat berupa :class:`Name`, :class:`Attribute`, atau :class:`Subscript`. ``annotation`` adalah anotasinya, seperti node :class:`Constant` atau :class:`Name`. ``value`` adalah satu node opsional.
``simple`` is always either 0 (indicating a "complex" target) or 1 (indicating a "simple" target). A "simple" target consists solely of a :class:`Name` node that does not appear between parentheses; all other targets are considered complex. Only simple targets appear in the :attr:`~object.__annotations__` dictionary of modules and classes.
``simple`` selalu bernilai 0 (menandakan target "kompleks") atau 1 (menandakan target "sederhana"). Target "sederhana" hanya terdiri dari node :class:`Name` yang tidak muncul di antara tanda kurung; semua target lainnya dianggap kompleks. Hanya target sederhana yang muncul di dictionary :attr:`~object.__annotations__` dari modul-Modul dan classes.
>>> print(ast.dump(ast.parse('c: int'), indent=4))
Module(
body=[
AnnAssign(
target=Name(id='c', ctx=Store()),
annotation=Name(id='int'),
simple=1)])
>>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis
Module(
body=[
AnnAssign(
target=Name(id='a', ctx=Store()),
annotation=Name(id='int'),
value=Constant(value=1),
simple=0)])
>>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation
Module(
body=[
AnnAssign(
target=Attribute(
value=Name(id='a'),
attr='b',
ctx=Store()),
annotation=Name(id='int'),
simple=0)])
>>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation
Module(
body=[
AnnAssign(
target=Subscript(
value=Name(id='a'),
slice=Constant(value=1),
ctx=Store()),
annotation=Name(id='int'),
simple=0)])
>>> print(ast.dump(ast.parse('c: int'), indent=4))
Module(
body=[
AnnAssign(
target=Name(id='c', ctx=Store()),
annotation=Name(id='int'),
simple=1)])
>>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Anotasi dengan tanda kurung
Module(
body=[
AnnAssign(
target=Name(id='a', ctx=Store()),
annotation=Name(id='int'),
value=Constant(value=1),
simple=0)])
>>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Anotasi atribut
Module(
body=[
AnnAssign(
target=Attribute(
value=Name(id='a'),
attr='b',
ctx=Store()),
annotation=Name(id='int'),
simple=0)])
>>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Anotasi subskrip
Module(
body=[
AnnAssign(
target=Subscript(
value=Name(id='a'),
slice=Constant(value=1),
ctx=Store()),
annotation=Name(id='int'),
simple=0)])
Augmented assignment, such as ``a += 1``. In the following example, ``target`` is a :class:`Name` node for ``x`` (with the :class:`Store` context), ``op`` is :class:`Add`, and ``value`` is a :class:`Constant` with value for 1.
Penugasan bertambah, seperti ``a += 1``. Pada contoh berikut, ``target`` adalah node :class:`Name` untuk ``x`` (dengan konteks :class:`Store`), ``op`` adalah :class:`Add`, dan ``value`` adalah :class:`Constant` dengan nilai 1.
The ``target`` attribute cannot be of class :class:`Tuple` or :class:`List`, unlike the targets of :class:`Assign`.
Atribut ``target`` tidak dapat berupa :class:`Tuple` atau :class:`List`, tidak seperti target pada :class:`Assign`.
>>> print(ast.dump(ast.parse('x += 2'), indent=4))
Module(
body=[
AugAssign(
target=Name(id='x', ctx=Store()),
op=Add(),
value=Constant(value=2))])
>>> print(ast.dump(ast.parse('x += 2'), indent=4))
Module(
body=[
AugAssign(
target=Name(id='x', ctx=Store()),
op=Add(),
value=Constant(value=2))])
A ``raise`` statement. ``exc`` is the exception object to be raised, normally a :class:`Call` or :class:`Name`, or ``None`` for a standalone ``raise``. ``cause`` is the optional part for ``y`` in ``raise x from y``.
Sebuah pernyataan ``raise``. ``exc`` adalah objek pengecualian yang akan dinaikkan, biasanya :class:`Call` atau :class:`Name`, atau ``None`` untuk ``raise`` tunggal. ``cause`` adalah bagian opsional untuk ``y`` dalam ``raise x from y``.
>>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
body=[
Raise(
exc=Name(id='x'),
cause=Name(id='y'))])
>>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
body=[
Raise(
exc=Name(id='x'),
cause=Name(id='y'))])
An assertion. ``test`` holds the condition, such as a :class:`Compare` node. ``msg`` holds the failure message.
Sebuah asersi. ``test`` menyimpan kondisi, seperti node :class:`Compare`. ``msg`` menyimpan pesan kegagalan.
>>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Module(
body=[
Assert(
test=Name(id='x'),
msg=Name(id='y'))])
>>> print(ast.dump(ast.parse('assert x,y'), indent=4))
Module(
body=[
Assert(
test=Name(id='x'),
msg=Name(id='y'))])
Represents a ``del`` statement. ``targets`` is a list of nodes, such as :class:`Name`, :class:`Attribute` or :class:`Subscript` nodes.
Mewakili pernyataan ``del``. ``targets`` adalah list node, seperti node :class:`Name`, :class:`Attribute`, atau :class:`Subscript`.
>>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Module(
body=[
Delete(
targets=[
Name(id='x', ctx=Del()),
Name(id='y', ctx=Del()),
Name(id='z', ctx=Del())])])
>>> print(ast.dump(ast.parse('del x,y,z'), indent=4))
Module(
body=[
Delete(
targets=[
Name(id='x', ctx=Del()),
Name(id='y', ctx=Del()),
Name(id='z', ctx=Del())])])
A ``pass`` statement.
Sebuah pernyataan ``pass``.
>>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
body=[
Pass()])
>>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
body=[
Pass()])
A :ref:`type alias <type-aliases>` created through the :keyword:`type` statement. ``name`` is the name of the alias, ``type_params`` is a list of :ref:`type parameters <ast-type-params>`, and ``value`` is the value of the type alias.
Sebuah :ref:`alias tipe <type-aliases>` yang dibuat melalui pernyataan :keyword:`type`. ``name`` adalah nama alias, ``type_params`` adalah list :ref:`parameter tipe <ast-type-params>`, dan ``value`` adalah nilai dari alias tipe.
>>> print(ast.dump(ast.parse('type Alias = int'), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
value=Name(id='int'))])
>>> print(ast.dump(ast.parse('type Alias = int'), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
value=Name(id='int'))])
Other statements which are only applicable inside functions or loops are described in other sections.
Pernyataan lain yang hanya berlaku di dalam fungsi-fungsi atau perulangan dijelaskan di bagian lain.
Imports
Impor
An import statement. ``names`` is a list of :class:`alias` nodes.
Sebuah pernyataan impor. ``names`` adalah list node :class:`alias`.
>>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Module(
body=[
Import(
names=[
alias(name='x'),
alias(name='y'),
alias(name='z')],
is_lazy=0)])
>>> print(ast.dump(ast.parse('import x,y,z'), indent=4))
Module(
body=[
Import(
names=[
alias(name='x'),
alias(name='y'),
alias(name='z')],
is_lazy=0)])
Represents ``from x import y``. ``module`` is a raw string of the 'from' name, without any leading dots, or ``None`` for statements such as ``from . import foo``. ``level`` is an integer holding the level of the relative import (0 means absolute import).
Mewakili ``from x import y``. ``module`` adalah string mentah dari nama 'from', tanpa titik awal apa pun, atau ``None`` untuk pernyataan seperti ``from . import foo``. ``level`` adalah bilangan bulat yang menyimpan level impor relatif (0 berarti impor absolut).
>>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Module(
body=[
ImportFrom(
module='y',
names=[
alias(name='x'),
alias(name='y'),
alias(name='z')],
level=0,
is_lazy=0)])
>>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))
Module(
body=[
ImportFrom(
module='y',
names=[
alias(name='x'),
alias(name='y'),
alias(name='z')],
level=0,
is_lazy=0)])
Both parameters are raw strings of the names. ``asname`` can be ``None`` if the regular name is to be used.
Kedua parameter adalah string mentah dari nama-nama. ``asname`` dapat bernilai ``None`` jika nama biasa akan digunakan.
>>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Module(
body=[
ImportFrom(
module='foo.bar',
names=[
alias(name='a', asname='b'),
alias(name='c')],
level=2,
is_lazy=0)])
>>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))
Module(
body=[
ImportFrom(
module='foo.bar',
names=[
alias(name='a', asname='b'),
alias(name='c')],
level=2,
is_lazy=0)])
Control flow
Alur kendali
Optional clauses such as ``else`` are stored as an empty list if they're not present.
Klausa opsional seperti ``else`` disimpan sebagai list kosong jika tidak ada.
An ``if`` statement. ``test`` holds a single node, such as a :class:`Compare` node. ``body`` and ``orelse`` each hold a list of nodes.
Sebuah pernyataan ``if``. ``test`` berisi satu node, seperti node :class:`Compare`. ``body`` dan ``orelse`` masing-masing berisi list node.
``elif`` clauses don't have a special representation in the AST, but rather appear as extra :class:`If` nodes within the ``orelse`` section of the previous one.
Klausa ``elif`` tidak memiliki representasi khusus di AST, tapi muncul sebagai node :class:`If` tambahan di dalam bagian ``orelse`` dari yang sebelumnya.
>>> print(ast.dump(ast.parse("""
... if x:
... ...
... elif y:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
If(
test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
If(
test=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... if x:
... ...
... elif y:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
If(
test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
If(
test=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])])
A ``for`` loop. ``target`` holds the variable(s) the loop assigns to, as a single :class:`Name`, :class:`Tuple`, :class:`List`, :class:`Attribute` or :class:`Subscript` node. ``iter`` holds the item to be looped over, again as a single node. ``body`` and ``orelse`` contain lists of nodes to execute. Those in ``orelse`` are executed if the loop finishes normally, rather than via a ``break`` statement.
Sebuah perulangan ``for``. ``target`` menyimpan variabel yang diisi oleh perulangan, sebagai satu node :class:`Name`, :class:`Tuple`, :class:`List`, :class:`Attribute` atau :class:`Subscript`. ``iter`` menyimpan item yang akan diiterasi, juga sebagai satu node. ``body`` dan ``orelse`` berisi list node yang akan dijalankan. Yang ada di ``orelse`` dijalankan jika perulangan berakhir normal, bukan melalui pernyataan ``break``.
>>> print(ast.dump(ast.parse("""
... for x in y:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
For(
target=Name(id='x', ctx=Store()),
iter=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])
>>> print(ast.dump(ast.parse("""
... for x in y:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
For(
target=Name(id='x', ctx=Store()),
iter=Name(id='y'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])
A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` node.
Sebuah perulangan ``while``. ``test`` menyimpan kondisi, seperti node :class:`Compare`.
>>> print(ast.dump(ast.parse("""
... while x:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
While(
test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])
>>> print(ast.dump(ast.parse("""
... while x:
... ...
... else:
... ...
... """), indent=4))
Module(
body=[
While(
test=Name(id='x'),
body=[
Expr(
value=Constant(value=Ellipsis))],
orelse=[
Expr(
value=Constant(value=Ellipsis))])])
The ``break`` and ``continue`` statements.
Pernyataan ``break`` dan ``continue``.
>>> print(ast.dump(ast.parse("""\
... for a in b:
... if a > 5:
... break
... else:
... continue
...
... """), indent=4))
Module(
body=[
For(
target=Name(id='a', ctx=Store()),
iter=Name(id='b'),
body=[
If(
test=Compare(
left=Name(id='a'),
ops=[
Gt()],
comparators=[
Constant(value=5)]),
body=[
Break()],
orelse=[
Continue()])])])
>>> print(ast.dump(ast.parse("""\
... for a in b:
... if a > 5:
... break
... else:
... continue
...
... """), indent=4))
Module(
body=[
For(
target=Name(id='a', ctx=Store()),
iter=Name(id='b'),
body=[
If(
test=Compare(
left=Name(id='a'),
ops=[
Gt()],
comparators=[
Constant(value=5)]),
body=[
Break()],
orelse=[
Continue()])])])
``try`` blocks. All attributes are list of nodes to execute, except for ``handlers``, which is a list of :class:`ExceptHandler` nodes.
Blok ``try``. Semua atribut adalah list node yang akan dijalankan, kecuali ``handlers``, yang merupakan list node :class:`ExceptHandler`.
>>> print(ast.dump(ast.parse("""
... try:
... ...
... except Exception:
... ...
... except OtherException as e:
... ...
... else:
... ...
... finally:
... ...
... """), indent=4))
Module(
body=[
Try(
body=[
Expr(
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))]),
ExceptHandler(
type=Name(id='OtherException'),
name='e',
body=[
Expr(
value=Constant(value=Ellipsis))])],
orelse=[
Expr(
value=Constant(value=Ellipsis))],
finalbody=[
Expr(
value=Constant(value=Ellipsis))])])
>>> print(ast.dump(ast.parse("""
... try:
... ...
... except Exception:
... ...
... except OtherException as e:
... ...
... else:
... ...
... finally:
... ...
... """), indent=4))
Module(
body=[
Try(
body=[
Expr(
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))]),
ExceptHandler(
type=Name(id='OtherException'),
name='e',
body=[
Expr(
value=Constant(value=Ellipsis))])],
orelse=[
Expr(
value=Constant(value=Ellipsis))],
finalbody=[
Expr(
value=Constant(value=Ellipsis))])])
``try`` blocks which are followed by ``except*`` clauses. The attributes are the same as for :class:`Try` but the :class:`ExceptHandler` nodes in ``handlers`` are interpreted as ``except*`` blocks rather than ``except``.
Blok ``try`` yang diikuti oleh klausa ``except*``. Atributnya sama seperti untuk :class:`Try` tapi node :class:`ExceptHandler` dalam ``handlers`` diinterpretasi sebagai blok ``except*`` alih-alih ``except``.
>>> print(ast.dump(ast.parse("""
... try:
... ...
... except* Exception:
... ...
... """), indent=4))
Module(
body=[
TryStar(
body=[
Expr(
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... try:
... ...
... except* Exception:
... ...
... """), indent=4))
Module(
body=[
TryStar(
body=[
Expr(
value=Constant(value=Ellipsis))],
handlers=[
ExceptHandler(
type=Name(id='Exception'),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
A single ``except`` clause. ``type`` is the exception type it will match, typically a :class:`Name` node (or ``None`` for a catch-all ``except:`` clause). ``name`` is a raw string for the name to hold the exception, or ``None`` if the clause doesn't have ``as foo``. ``body`` is a list of nodes.
Satu klausa ``except``. ``type`` adalah tipe pengecualian yang akan dicocokkan, biasanya node :class:`Name` (atau ``None`` untuk klausa ``except:`` yang menangkap semua). ``name`` adalah string mentah untuk nama yang menampung pengecualian, atau ``None`` jika klausa tidak memiliki ``as foo``. ``body`` adalah list node.
>>> print(ast.dump(ast.parse("""\
... try:
... a + 1
... except TypeError:
... pass
... """), indent=4))
Module(
body=[
Try(
body=[
Expr(
value=BinOp(
left=Name(id='a'),
op=Add(),
right=Constant(value=1)))],
handlers=[
ExceptHandler(
type=Name(id='TypeError'),
body=[
Pass()])])])
>>> print(ast.dump(ast.parse("""\
... try:
... a + 1
... except TypeError:
... pass
... """), indent=4))
Module(
body=[
Try(
body=[
Expr(
value=BinOp(
left=Name(id='a'),
op=Add(),
right=Constant(value=1)))],
handlers=[
ExceptHandler(
type=Name(id='TypeError'),
body=[
Pass()])])])
A ``with`` block. ``items`` is a list of :class:`withitem` nodes representing the context managers, and ``body`` is the indented block inside the context.
Sebuah blok ``with``. ``items`` adalah list node :class:`withitem` yang merepresentasikan manajer konteks, dan ``body`` adalah blok berinden di dalam konteks.
A single context manager in a ``with`` block. ``context_expr`` is the context manager, often a :class:`Call` node. ``optional_vars`` is a :class:`Name`, :class:`Tuple` or :class:`List` for the ``as foo`` part, or ``None`` if that isn't used.
Satu manajer konteks dalam blok ``with``. ``context_expr`` adalah manajer konteks, sering kali berupa node :class:`Call`. ``optional_vars`` adalah :class:`Name`, :class:`Tuple` atau :class:`List` untuk bagian ``as foo``, atau ``None`` jika itu tidak digunakan.
>>> print(ast.dump(ast.parse("""\
... with a as b, c as d:
... something(b, d)
... """), indent=4))
Module(
body=[
With(
items=[
withitem(
context_expr=Name(id='a'),
optional_vars=Name(id='b', ctx=Store())),
withitem(
context_expr=Name(id='c'),
optional_vars=Name(id='d', ctx=Store()))],
body=[
Expr(
value=Call(
func=Name(id='something'),
args=[
Name(id='b'),
Name(id='d')]))])])
>>> print(ast.dump(ast.parse("""\
... with a as b, c as d:
... something(b, d)
... """), indent=4))
Module(
body=[
With(
items=[
withitem(
context_expr=Name(id='a'),
optional_vars=Name(id='b', ctx=Store())),
withitem(
context_expr=Name(id='c'),
optional_vars=Name(id='d', ctx=Store()))],
body=[
Expr(
value=Call(
func=Name(id='something'),
args=[
Name(id='b'),
Name(id='d')]))])])
Pattern matching
Pencocokan pola
A ``match`` statement. ``subject`` holds the subject of the match (the object that is being matched against the cases) and ``cases`` contains an iterable of :class:`match_case` nodes with the different cases.
Sebuah pernyataan ``match``. ``subject`` memuat subjek pencocokan (objek yang dicocokkan terhadap kasus-kasus) dan ``cases`` berisi iterable node :class:`match_case` dengan berbagai kasus.
A single case pattern in a ``match`` statement. ``pattern`` contains the match pattern that the subject will be matched against. Note that the :class:`AST` nodes produced for patterns differ from those produced for expressions, even when they share the same syntax.
Satu pola kasus dalam pernyataan ``match``. ``pattern`` berisi pola pencocokan yang akan dicocokkan dengan subjek. Perhatikan bahwa node :class:`AST` yang dihasilkan untuk pola berbeda dari yang dihasilkan untuk ekspresi, bahkan ketika mereka berbagi sintaksis yang sama.
The ``guard`` attribute contains an expression that will be evaluated if the pattern matches the subject.
Atribut ``guard`` berisi sebuah ekspresi yang akan dievaluasi jika polanya cocok dengan subjek.
``body`` contains a list of nodes to execute if the pattern matches and the result of evaluating the guard expression is true.
``body`` berisi list node yang akan dieksekusi jika polanya cocok dan hasil evaluasi ekspresi guard adalah true.
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] if x>0:
... ...
... case tuple():
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
patterns=[
MatchAs(name='x')]),
guard=Compare(
left=Name(id='x'),
ops=[
Gt()],
comparators=[
Constant(value=0)]),
body=[
Expr(
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
cls=Name(id='tuple')),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] if x>0:
... ...
... case tuple():
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
patterns=[
MatchAs(name='x')]),
guard=Compare(
left=Name(id='x'),
ops=[
Gt()],
comparators=[
Constant(value=0)]),
body=[
Expr(
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
cls=Name(id='tuple')),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
A match literal or value pattern that compares by equality. ``value`` is an expression node. Permitted value nodes are restricted as described in the match statement documentation. This pattern succeeds if the match subject is equal to the evaluated value.
Literal pencocokan atau pola nilai yang membandingkan berdasarkan kesamaan. ``value`` adalah node ekspresi. Node nilai yang diizinkan dibatasi seperti dijelaskan dalam dokumentasi pernyataan match. Pola ini berhasil jika subjek pencocokan sama dengan nilai yang dievaluasi.
>>> print(ast.dump(ast.parse("""
... match x:
... case "Relevant":
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchValue(
value=Constant(value='Relevant')),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case "Relevant":
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchValue(
value=Constant(value='Relevant')),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
A match literal pattern that compares by identity. ``value`` is the singleton to be compared against: ``None``, ``True``, or ``False``. This pattern succeeds if the match subject is the given constant.
Suatu pola pencocokan literal yang membandingkan berdasarkan identitas. ``nilai`` adalah singleton yang akan dibandingkan: ``None``, ``True``, atau ``False``. Pola ini berhasil jika subjek pencocokan adalah konstanta yang diberikan.
>>> print(ast.dump(ast.parse("""
... match x:
... case None:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSingleton(value=None),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case None:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSingleton(value=None),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
A match sequence pattern. ``patterns`` contains the patterns to be matched against the subject elements if the subject is a sequence. Matches a variable length sequence if one of the subpatterns is a ``MatchStar`` node, otherwise matches a fixed length sequence.
Pola urutan pencocokan. ``patterns`` berisi pola-pola yang akan dicocokkan dengan elemen subjek jika subjek berupa urutan. Mencocokkan urutan dengan panjang variabel jika salah satu subpola adalah node ``MatchStar``, jika tidak maka mencocokkan urutan dengan panjang tetap.
>>> print(ast.dump(ast.parse("""
... match x:
... case [1, 2]:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
patterns=[
MatchValue(
value=Constant(value=1)),
MatchValue(
value=Constant(value=2))]),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case [1, 2]:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchSequence(
patterns=[
MatchValue(
value=Constant(value=1)),
MatchValue(
value=Constant(value=2))]),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
Matches the rest of the sequence in a variable length match sequence pattern. If ``name`` is not ``None``, a list containing the remaining sequence elements is bound to that name if the overall sequence pattern is successful.
Mencocokkan sisa urutan dalam pola urutan pencocokan dengan panjang variabel. Jika ``nama`` tidak ``None``, sebuah list yang berisi elemen urutan yang tersisa akan diikat ke nama tersebut jika pola urutan secara keseluruhan berhasil.
>>> print(ast.dump(ast.parse("""
... match x:
... case [1, 2, *rest]:
... ...
... case [*_]:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case [1, 2, *rest]:
... ...
... case [*_]:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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))])])])
A match mapping pattern. ``keys`` is a sequence of expression nodes. ``patterns`` is a corresponding sequence of pattern nodes. ``rest`` is an optional name that can be specified to capture the remaining mapping elements. Permitted key expressions are restricted as described in the match statement documentation.
Pola pemetaan pencocokan. ``keys`` adalah urutan node ekspresi. ``patterns`` adalah urutan node pola yang bersesuaian. ``rest`` adalah nama opsional yang dapat ditentukan untuk menangkap elemen pemetaan yang tersisa. Ekspresi *Key* yang diizinkan dibatasi sebagaimana dijelaskan dalam dokumentasi pernyataan match.
This pattern succeeds if the subject is a mapping, all evaluated key expressions are present in the mapping, and the value corresponding to each key matches the corresponding subpattern. If ``rest`` is not ``None``, a dict containing the remaining mapping elements is bound to that name if the overall mapping pattern is successful.
Pola ini berhasil jika subjek adalah pemetaan, semua ekspresi *Key* yang dievaluasi ada dalam pemetaan, dan nilai yang bersesuaian untuk setiap *Key* cocok dengan subpola yang bersesuaian. Jika ``rest`` tidak ``None``, sebuah dict yang berisi elemen pemetaan yang tersisa diikat ke nama tersebut jika pola pemetaan secara keseluruhan berhasil.
>>> print(ast.dump(ast.parse("""
... match x:
... case {1: _, 2: _}:
... ...
... case {**rest}:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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(rest='rest'),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case {1: _, 2: _}:
... ...
... case {**rest}:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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(rest='rest'),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
A match class pattern. ``cls`` is an expression giving the nominal class to be matched. ``patterns`` is a sequence of pattern nodes to be matched against the class defined sequence of pattern matching attributes. ``kwd_attrs`` is a sequence of additional attributes to be matched (specified as keyword arguments in the class pattern), ``kwd_patterns`` are the corresponding patterns (specified as keyword values in the class pattern).
Pola kelas untuk pencocokan. ``cls`` adalah ekspresi yang memberikan kelas nominal yang akan dicocokkan. ``patterns`` adalah urutan node pola yang akan dicocokkan terhadap urutan atribut pencocokan pola yang didefinisikan oleh kelas. ``kwd_attrs`` adalah urutan atribut tambahan yang akan dicocokkan (ditentukan sebagai argumen Kata Kunci *Keyword Arguments* dalam pola kelas), ``kwd_patterns`` adalah pola-pola yang bersesuaian (ditentukan sebagai nilai kata kunci dalam pola kelas).
This pattern succeeds if the subject is an instance of the nominated class, all positional patterns match the corresponding class-defined attributes, and any specified keyword attributes match their corresponding pattern.
Pola ini berhasil jika subjek adalah instans dari kelas yang ditentukan, semua pola posisional cocok dengan atribut yang ditentukan oleh kelas, dan setiap atribut kata kunci yang ditentukan cocok dengan polanya yang bersesuaian.
Note: classes may define a property that returns self in order to match a pattern node against the instance being matched. Several builtin types are also matched that way, as described in the match statement documentation.
Catatan: classes dapat mendefinisikan properti yang mengembalikan self untuk mencocokkan sebuah node pola terhadap instans yang sedang dicocokkan. Beberapa types bawaan juga dicocokkan dengan cara itu, sebagaimana dijelaskan dalam dokumentasi pernyataan match.
>>> print(ast.dump(ast.parse("""
... match x:
... case Point2D(0, 0):
... ...
... case Point3D(x=0, y=0, z=0):
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchClass(
cls=Name(id='Point2D'),
patterns=[
MatchValue(
value=Constant(value=0)),
MatchValue(
value=Constant(value=0))]),
body=[
Expr(
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
cls=Name(id='Point3D'),
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))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case Point2D(0, 0):
... ...
... case Point3D(x=0, y=0, z=0):
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchClass(
cls=Name(id='Point2D'),
patterns=[
MatchValue(
value=Constant(value=0)),
MatchValue(
value=Constant(value=0))]),
body=[
Expr(
value=Constant(value=Ellipsis))]),
match_case(
pattern=MatchClass(
cls=Name(id='Point3D'),
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))])])])
A match "as-pattern", capture pattern or wildcard pattern. ``pattern`` contains the match pattern that the subject will be matched against. If the pattern is ``None``, the node represents a capture pattern (i.e a bare name) and will always succeed.
Sebuah pola "as-pattern", pola penangkap, atau pola wildcard. ``pattern`` berisi pola pencocokan yang akan dicocokkan terhadap subjek. Jika polanya adalah ``None``, node ini merepresentasikan pola penangkap (yaitu sebuah nama polos) dan akan selalu berhasil.
The ``name`` attribute contains the name that will be bound if the pattern is successful. If ``name`` is ``None``, ``pattern`` must also be ``None`` and the node represents the wildcard pattern.
Atribut ``name`` berisi nama yang akan diikat jika polanya berhasil. Jika ``name`` adalah ``None``, ``pattern`` juga harus ``None`` dan node ini merepresentasikan pola wildcard.
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] as y:
... ...
... case _:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] as y:
... ...
... case _:
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
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))])])])
A match "or-pattern". An or-pattern matches each of its subpatterns in turn to the subject, until one succeeds. The or-pattern is then deemed to succeed. If none of the subpatterns succeed the or-pattern fails. The ``patterns`` attribute contains a list of match pattern nodes that will be matched against the subject.
Sebuah pola "or-pattern". Sebuah or-pattern mencocokkan setiap subpolanya secara bergiliran terhadap subjek hingga salah satunya berhasil. Or-pattern tersebut kemudian dianggap berhasil. Jika tidak ada subpola yang berhasil, or-pattern gagal. Atribut ``patterns`` berisi list node pola pencocokan yang akan dicocokkan terhadap subjek.
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] | (y):
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchOr(
patterns=[
MatchSequence(
patterns=[
MatchAs(name='x')]),
MatchAs(name='y')]),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
>>> print(ast.dump(ast.parse("""
... match x:
... case [x] | (y):
... ...
... """), indent=4))
Module(
body=[
Match(
subject=Name(id='x'),
cases=[
match_case(
pattern=MatchOr(
patterns=[
MatchSequence(
patterns=[
MatchAs(name='x')]),
MatchAs(name='y')]),
body=[
Expr(
value=Constant(value=Ellipsis))])])])
Type annotations
Anotasi tipe
A ``# type: ignore`` comment located at *lineno*. *tag* is the optional tag specified by the form ``# type: ignore <tag>``.
Sebuah komentarz ``# type: ignore`` yang terletak pada *lineno*. *tag* adalah tag opsional yang ditentukan oleh bentuk ``# type: ignore <tag>``.
>>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1))],
type_ignores=[
TypeIgnore(lineno=1, tag='')])
>>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4))
Module(
body=[
AnnAssign(
target=Name(id='x', ctx=Store()),
annotation=Name(id='bool'),
value=Constant(value=1),
simple=1)],
type_ignores=[
TypeIgnore(lineno=1, tag='[assignment]')])
>>> print(ast.dump(ast.parse('x = 1 # type: ignore', type_comments=True), indent=4))
Module(
body=[
Assign(
targets=[
Name(id='x', ctx=Store())],
value=Constant(value=1))],
type_ignores=[
TypeIgnore(lineno=1, tag='')])
>>> print(ast.dump(ast.parse('x: bool = 1 # type: ignore[assignment]', type_comments=True), indent=4))
Module(
body=[
AnnAssign(
target=Name(id='x', ctx=Store()),
annotation=Name(id='bool'),
value=Constant(value=1),
simple=1)],
type_ignores=[
TypeIgnore(lineno=1, tag='[assignment]')])
:class:`!TypeIgnore` nodes are not generated when the *type_comments* parameter is set to ``False`` (default). See :func:`ast.parse` for more details.
Node :class:`!TypeIgnore` tidak dibuat saat parameter *type_comments* di-set ke ``False`` (bawaan). Lihat :func:`ast.parse` untuk detail lebih lanjut.
Type parameters
Parameter tipe
:ref:`Type parameters <type-params>` can exist on classes, functions, and type aliases.
:ref:`Parameter tipe <type-params>` dapat ada pada classes, fungsi-Fungsi, dan alias tipe.
A :class:`typing.TypeVar`. ``name`` is the name of the type variable. ``bound`` is the bound or constraints, if any. If ``bound`` is a :class:`Tuple`, it represents constraints; otherwise it represents the bound. ``default_value`` is the default value; if the :class:`!TypeVar` has no default, this attribute will be set to ``None``.
Sebuah :class:`typing.TypeVar`. ``name`` adalah nama variabel tipe. ``bound`` adalah batas atau kendala, jika ada. Jika ``bound`` adalah :class:`Tuple`, itu merepresentasikan kendala; jika tidak, itu merepresentasikan batas. ``default_value`` adalah nilai bawaan; jika :class:`!TypeVar` tidak memiliki bawaan, atribut ini akan di-set ke ``None``.
>>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
TypeVar(
name='T',
bound=Name(id='int'),
default_value=Name(id='bool'))],
value=Subscript(
value=Name(id='list'),
slice=Name(id='T')))])
>>> print(ast.dump(ast.parse("type Alias[T: int = bool] = list[T]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
TypeVar(
name='T',
bound=Name(id='int'),
default_value=Name(id='bool'))],
value=Subscript(
value=Name(id='list'),
slice=Name(id='T'))])
Added the *default_value* parameter.
Menambahkan parameter *default_value*.
A :class:`typing.ParamSpec`. ``name`` is the name of the parameter specification. ``default_value`` is the default value; if the :class:`!ParamSpec` has no default, this attribute will be set to ``None``.
Sebuah :class:`typing.ParamSpec`. ``name`` adalah nama spesifikasi parameter. ``default_value`` adalah nilai bawaan; jika :class:`!ParamSpec` tidak memiliki bawaan, atribut ini akan di-set ke ``None``.
>>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
ParamSpec(
name='P',
default_value=List(
elts=[
Name(id='int'),
Name(id='str')]))],
value=Subscript(
value=Name(id='Callable'),
slice=Tuple(
elts=[
Name(id='P'),
Name(id='int')])))])
>>> print(ast.dump(ast.parse("type Alias[**P = [int, str]] = Callable[P, int]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
ParamSpec(
name='P',
default_value=List(
elts=[
Name(id='int'),
Name(id='str')]))],
value=Subscript(
value=Name(id='Callable'),
slice=Tuple(
elts=[
Name(id='P'),
Name(id='int')])))])
A :class:`typing.TypeVarTuple`. ``name`` is the name of the type variable tuple. ``default_value`` is the default value; if the :class:`!TypeVarTuple` has no default, this attribute will be set to ``None``.
Sebuah :class:`typing.TypeVarTuple`. ``name`` adalah nama tupel variabel tipe. ``default_value`` adalah nilai bawaan; jika :class:`!TypeVarTuple` tidak memiliki bawaan, atribut ini akan di-set ke ``None``.
>>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
TypeVarTuple(name='Ts', default_value=Tuple())],
value=Subscript(
value=Name(id='tuple'),
slice=Tuple(
elts=[
Starred(
value=Name(id='Ts'))])))])
>>> print(ast.dump(ast.parse("type Alias[*Ts = ()] = tuple[*Ts]"), indent=4))
Module(
body=[
TypeAlias(
name=Name(id='Alias', ctx=Store()),
type_params=[
TypeVarTuple(name='Ts', default_value=Tuple())],
value=Subscript(
value=Name(id='tuple'),
slice=Tuple(
elts=[
Starred(
value=Name(id='Ts'))])))])
Function and class definitions
Definisi fungsi dan kelas
A function definition.
Sebuah definisi fungsi.
``name`` is a raw string of the function name.
``name`` adalah string mentah dari nama fungsi.
``args`` is an :class:`arguments` node.
``args`` adalah node :class:`arguments`.
``body`` is the list of nodes inside the function.
``body`` adalah list node di dalam fungsi.
``decorator_list`` is the list of decorators to be applied, stored outermost first (i.e. the first in the list will be applied last).
``decorator_list`` adalah list decorator yang akan diterapkan, disimpan dari yang terluar terlebih dahulu (yaitu yang pertama dalam list akan diterapkan terakhir).
``returns`` is the return annotation.
``returns`` adalah anotasi pengembalian.
``type_params`` is a list of :ref:`type parameters <ast-type-params>`.
``type_params`` adalah list :ref:`parameter tipe <ast-type-params>`.
Added ``type_params``.
Ditambahkan ``type_params``.
``lambda`` is a minimal function definition that can be used inside an expression. Unlike :class:`FunctionDef`, ``body`` holds a single node.
``lambda`` adalah definisi fungsi minimal yang dapat digunakan di dalam sebuah ekspresi. Tidak seperti :class:`FunctionDef`, ``body`` berisi satu node.
>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Module(
body=[
Expr(
value=Lambda(
args=arguments(
args=[
arg(arg='x'),
arg(arg='y')]),
body=Constant(value=Ellipsis)))])
>>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))
Module(
body=[
Expr(
value=Lambda(
args=arguments(
args=[
arg(arg='x'),
arg(arg='y')]),
body=Constant(value=Ellipsis)))])
The arguments for a function.
Argumen untuk sebuah fungsi.
``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` nodes.
``posonlyargs``, ``args`` dan ``kwonlyargs`` adalah list node :class:`arg`.
``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the ``*args, **kwargs`` parameters.
``vararg`` dan ``kwarg`` adalah node :class:`arg` tunggal, merujuk ke parameter ``*args, **kwargs``.
``kw_defaults`` is a list of default values for keyword-only arguments. If one is ``None``, the corresponding argument is required.
``kw_defaults`` adalah list nilai bawaan untuk argumen kata kunci-saja. Jika salah satunya ``None``, argumen yang bersangkutan diperlukan.
``defaults`` is a list of default values for arguments that can be passed positionally. If there are fewer defaults, they correspond to the last n arguments.
``defaults`` adalah list nilai bawaan untuk argumen yang dapat diberikan secara posisional. Jika jumlah nilai bawaan lebih sedikit, nilai-nilai tersebut sesuai dengan n argumen terakhir.
A single argument in a list. ``arg`` is a raw string of the argument name; ``annotation`` is its annotation, such as a :class:`Name` node.
Satu argumen dalam sebuah list. ``arg`` adalah string mentah dari nama argumen; ``annotation`` adalah anotasinya, seperti node :class:`Name`.
``type_comment`` is an optional string with the type annotation as a comment
``type_comment`` adalah string opsional dengan anotasi tipe sebagai komentarz
>>> print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
... pass
... """), indent=4))
Module(
body=[
FunctionDef(
name='f',
args=arguments(
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'),
Name(id='decorator2')],
returns=Constant(value='return annotation'))])
>>> print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':
... pass
... """), indent=4))
Module(
body=[
FunctionDef(
name='f',
args=arguments(
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'),
Name(id='decorator2')],
returns=Constant(value='return annotation'))])
A ``return`` statement.
Sebuah pernyataan ``return``.
>>> print(ast.dump(ast.parse('return 4'), indent=4))
Module(
body=[
Return(
value=Constant(value=4))])
>>> print(ast.dump(ast.parse('return 4'), indent=4))
Module(
body=[
Return(
value=Constant(value=4))])
A ``yield`` or ``yield from`` expression. Because these are expressions, they must be wrapped in an :class:`Expr` node if the value sent back is not used.
Sebuah ekspresi ``yield`` atau ``yield from``. Karena ini adalah ekspresi, ekspresi tersebut harus dibungkus dalam node :class:`Expr` jika nilai yang dikirim balik tidak digunakan.
>>> print(ast.dump(ast.parse('yield x'), indent=4))
Module(
body=[
Expr(
value=Yield(
value=Name(id='x')))])
>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
body=[
Expr(
value=YieldFrom(
value=Name(id='x')))])
>>> print(ast.dump(ast.parse('yield x'), indent=4))
Module(
body=[
Expr(
value=Yield(
value=Name(id='x')))])
>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
body=[
Expr(
value=YieldFrom(
value=Name(id='x')))])
``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings.
Pernyataan ``global`` dan ``nonlocal``. ``names`` adalah list string mentah.
>>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Module(
body=[
Global(
names=[
'x',
'y',
'z'])])
>>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Module(
body=[
Nonlocal(
names=[
'x',
'y',
'z'])])
>>> print(ast.dump(ast.parse('global x,y,z'), indent=4))
Module(
body=[
Global(
names=[
'x',
'y',
'z'])])
>>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))
Module(
body=[
Nonlocal(
names=[
'x',
'y',
'z'])])
A class definition.
Definisi kelas.
``name`` is a raw string for the class name
``name`` adalah string mentah untuk nama kelas
``bases`` is a list of nodes for explicitly specified base classes.
``bases`` adalah list node untuk classes dasar yang ditentukan secara eksplisit.
``keywords`` is a list of :class:`.keyword` nodes, principally for 'metaclass'. Other keywords will be passed to the metaclass, as per :pep:`3115`.
``keywords`` adalah list node :class:`.keyword`, terutama untuk 'metaklasa'. Kata kunci lain akan diteruskan ke metaklasa, sesuai :pep:`3115`.
``body`` is a list of nodes representing the code within the class definition.
``body`` adalah list node yang merepresentasikan code di dalam definisi kelas.
``decorator_list`` is a list of nodes, as in :class:`FunctionDef`.
``decorator_list`` adalah list node, seperti pada :class:`FunctionDef`.
>>> print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... class Foo(base1, base2, metaclass=meta):
... pass
... """), indent=4))
Module(
body=[
ClassDef(
name='Foo',
bases=[
Name(id='base1'),
Name(id='base2')],
keywords=[
keyword(
arg='metaclass',
value=Name(id='meta'))],
body=[
Pass()],
decorator_list=[
Name(id='decorator1'),
Name(id='decorator2')])])
>>> print(ast.dump(ast.parse("""\
... @decorator1
... @decorator2
... class Foo(base1, base2, metaclass=meta):
... pass
... """), indent=4))
Module(
body=[
ClassDef(
name='Foo',
bases=[
Name(id='base1'),
Name(id='base2')],
keywords=[
keyword(
arg='metaclass',
value=Name(id='meta'))],
body=[
Pass()],
decorator_list=[
Name(id='decorator1'),
Name(id='decorator2')])])
Async and await
Async dan await
An ``async def`` function definition. Has the same fields as :class:`FunctionDef`.
Definisi fungsi ``async def``. Memiliki field yang sama seperti :class:`FunctionDef`.
An ``await`` expression. ``value`` is what it waits for. Only valid in the body of an :class:`AsyncFunctionDef`.
Sebuah ekspresi ``await``. ``value`` adalah apa yang ditunggunya. Hanya valid di dalam body dari :class:`AsyncFunctionDef`.
>>> print(ast.dump(ast.parse("""\
... async def f():
... await other_func()
... """), indent=4))
Module(
body=[
AsyncFunctionDef(
name='f',
args=arguments(),
body=[
Expr(
value=Await(
value=Call(
func=Name(id='other_func'))))])])
>>> print(ast.dump(ast.parse("""\
... async def f():
... await other_func()
... """), indent=4))
Module(
body=[
AsyncFunctionDef(
name='f',
args=arguments(),
body=[
Expr(
value=Await(
value=Call(
func=Name(id='other_func'))))])])
``async for`` loops and ``async with`` context managers. They have the same fields as :class:`For` and :class:`With`, respectively. Only valid in the body of an :class:`AsyncFunctionDef`.
Perulangan ``async for`` dan manajer konteks ``async with``. Mereka memiliki field yang sama seperti :class:`For` dan :class:`With`, masing-masing. Hanya valid di dalam body dari :class:`AsyncFunctionDef`.
When a string is parsed by :func:`ast.parse`, operator nodes (subclasses of :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, :class:`ast.boolop` and :class:`ast.expr_context`) on the returned tree will be singletons. Changes to one will be reflected in all other occurrences of the same value (for example, :class:`ast.Add`).
Ketika sebuah string diurai oleh :func:`ast.parse`, node operator (subkelas dari :class:`ast.operator`, :class:`ast.unaryop`, :class:`ast.cmpop`, :class:`ast.boolop` dan :class:`ast.expr_context`) pada pohon yang dikembalikan akan berupa singleton. Perubahan pada satu akan tercermin pada semua kemunculan lain dari nilai yang sama (sebagai contoh, :class:`ast.Add`).
:mod:`!ast` helpers
Pembantu :mod:`!ast`
Apart from the node classes, the :mod:`!ast` module defines these utility functions and classes for traversing abstract syntax trees:
Selain classes node, modul :mod:`!ast` mendefinisikan fungsi-Fungsi utilitas dan classes untuk menelusuri pohon sintaksis abstrak:
Parse the source into an AST node. Equivalent to ``compile(source, filename, mode, flags=FLAGS_VALUE, optimize=optimize, module=module)``, where ``FLAGS_VALUE`` is ``ast.PyCF_ONLY_AST`` if ``optimize <= 0`` and ``ast.PyCF_OPTIMIZED_AST`` otherwise.
Uraikan source menjadi node AST. Setara dengan ``compile(source, filename, mode, flags=FLAGS_VALUE, optimize=optimize, module=module)``, di mana ``FLAGS_VALUE`` adalah ``ast.PyCF_ONLY_AST`` jika ``optimize <= 0`` dan ``ast.PyCF_OPTIMIZED_AST`` selain itu.
If ``type_comments=True`` is given, the parser is modified to check and return type comments as specified by :pep:`484` and :pep:`526`. This is equivalent to adding :data:`ast.PyCF_TYPE_COMMENTS` to the flags passed to :func:`compile`. This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the ``type_comment`` field on selected AST nodes will always be ``None``. In addition, the locations of ``# type: ignore`` comments will be returned as the ``type_ignores`` attribute of :class:`Module` (otherwise it is always an empty list).
Selain itu, jika ``type_comments=True`` diberikan, parser diubah untuk memeriksa dan mengembalikan komentar tipe sebagaimana ditentukan oleh :pep:`484` dan :pep:`526`. Ini setara dengan menambahkan :data:`ast.PyCF_TYPE_COMMENTS` ke penanda yang diteruskan ke :func:`compile`. Ini akan melaporkan kesalahan Sintaksis untuk komentar tipe yang salah tempat. Tanpa penanda ini, komentar tipe akan diabaikan, dan field ``type_comment`` pada node-node AST tertentu akan selalu ``None``. Selain itu, lokasi komentar ``# type: ignore`` akan dikembalikan sebagai atribut ``type_ignores`` dari :class:`Module` (kalau tidak, ia selalu berupa list kosong).
In addition, if ``mode`` is ``'func_type'``, the input syntax is modified to correspond to :pep:`484` "signature type comments", for example ``(str, int) -> List[str]``.
Selain itu, jika ``mode`` adalah ``'func_type'``, sintaksis masukan diubah agar sesuai dengan :pep:`484` “komentar tipe tanda tangan”, sebagai contoh ``(str, int) -> List[str]``.
Setting ``feature_version`` to a tuple ``(major, minor)`` will result in a "best-effort" attempt to parse using that Python version's grammar. For example, setting ``feature_version=(3, 9)`` will attempt to disallow parsing of :keyword:`match` statements. Currently ``major`` must equal to ``3``. The lowest supported version is ``(3, 7)`` (and this may increase in future Python versions); the highest is ``sys.version_info[0:2]``. "Best-effort" attempt means there is no guarantee that the parse (or success of the parse) is the same as when run on the Python version corresponding to ``feature_version``.
Mengatur ``feature_version`` ke sebuah tupel ``(major, minor)`` akan menghasilkan upaya "sebaik-mungkin" untuk mengurai menggunakan tata bahasa versi Python tersebut. Sebagai contoh, mengatur ``feature_version=(3, 9)`` akan mencoba melarang penguraian pernyataan :keyword:`match`. Saat ini ``major`` harus sama dengan ``3``. Versi terendah yang didukung adalah ``(3, 7)`` (dan ini dapat meningkat pada versi Python mendatang); yang tertinggi adalah ``sys.version_info[0:2]``. "Sebaik-mungkin" berarti tidak ada jaminan bahwa penguraian (atau keberhasilan penguraian) sama seperti saat dijalankan pada versi Python yang sesuai dengan ``feature_version``.
If source contains a null character (``\0``), :exc:`ValueError` is raised.
Jika source berisi karakter NULL (``\0``), :exc:`ValueError` akan dinaikkan.
Note that successfully parsing source code into an AST object doesn't guarantee that the source code provided is valid Python code that can be executed as the compilation step can raise further :exc:`SyntaxError` exceptions. For instance, the source ``return 42`` generates a valid AST node for a return statement, but it cannot be compiled alone (it needs to be inside a function node).
Perhatikan bahwa berhasil mengurai source code menjadi objek AST tidak menjamin bahwa source code yang diberikan adalah code Python yang valid dan dapat dieksekusi, karena tahap kompilasi dapat menimbulkan pengecualian :exc:`SyntaxError` lebih lanjut. Misalnya, source ``return 42`` menghasilkan node AST yang valid untuk pernyataan return, tapi ia tidak dapat dikompilasi sendirian (perlu berada di dalam node fungsi).
In particular, :func:`ast.parse` won't do any scoping checks, which the compilation step does.
Secara khusus, :func:`ast.parse` tidak akan melakukan pemeriksaan cakupan apa pun, yang dilakukan oleh tahap kompilasi.
It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python's AST compiler.
Dimungkinkan untuk membuat interpreter Python crash dengan string yang cukup besar/kompleks karena keterbatasan kedalaman stack pada kompiler AST Python.
Added ``type_comments``, ``mode='func_type'`` and ``feature_version``.
Menambahkan ``type_comments``, ``mode='func_type'`` dan ``feature_version``.
The minimum supported version for ``feature_version`` is now ``(3, 7)``. The ``optimize`` argument was added.
Versi minimum yang didukung untuk ``feature_version`` sekarang ``(3, 7)``. Argumen ``optimize`` telah ditambahkan.
Added the *module* parameter.
Menambahkan parameter *module*.
Unparse an :class:`ast.AST` object and generate a string with code that would produce an equivalent :class:`ast.AST` object if parsed back with :func:`ast.parse`.
Melakukan unparse pada sebuah objek :class:`ast.AST` dan menghasilkan sebuah string dengan code yang akan menghasilkan objek :class:`ast.AST` yang ekuivalen jika di-parse kembali dengan :func:`ast.parse`.
The produced code string will not necessarily be equal to the original code that generated the :class:`ast.AST` object (without any compiler optimizations, such as constant tuples/frozensets).
String code yang dihasilkan tidak harus sama dengan code asli yang menghasilkan objek :class:`ast.AST` (tanpa optimalisasi kompiler, seperti konstanta *Tuples*/frozensets).
Trying to unparse a highly complex expression would result with :exc:`RecursionError`.
Mencoba melakukan unparse pada ekspresi yang sangat kompleks akan menghasilkan :exc:`RecursionError`.
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, ``None`` and ``Ellipsis``.
Evaluasi sebuah node ekspresi atau sebuah string yang hanya berisi literal Python atau tampilan kontainer. String atau node yang diberikan hanya boleh terdiri dari struktur literal Python berikut: string, bytes, angka, *Tuples*, list, dict, himpunan *Set*, boolean, ``None`` dan ``Ellipsis``.
This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Ini dapat digunakan untuk mengevaluasi string yang berisi nilai Python tanpa perlu melakukan parsing nilai tersebut sendiri. Ini tidak mampu mengevaluasi ekspresi yang sewenang-wenang kompleks, sebagai contoh yang melibatkan operator atau pengindeksan.
This function had been documented as "safe" in the past without defining what that meant. That was misleading. This is specifically designed not to execute Python code, unlike the more general :func:`eval`. There is no namespace, no name lookups, or ability to call out. But it is not free from attack: A relatively small input can lead to memory exhaustion or to C stack exhaustion, crashing the process. There is also the possibility for excessive CPU consumption denial of service on some inputs. Calling it on untrusted data is thus not recommended.
Fungsi ini dahulu telah didokumentasikan sebagai "aman" tanpa mendefinisikan apa artinya. Itu menyesatkan. Ini secara khusus dirancang untuk tidak mengeksekusi code Python, tidak seperti :func:`eval` yang lebih umum. Tidak ada namespace, tidak ada pencarian nama, atau kemampuan untuk melakukan pemanggilan keluar. Tapi ini tidak bebas dari serangan: Masukan yang relatif kecil dapat menyebabkan kehabisan memori atau kehabisan stack C, sehingga proses crash. Ada juga kemungkinan penolakan layanan karena konsumsi CPU berlebihan pada beberapa masukan. Karena itu, memanggilnya pada data yang tidak tepercaya tidak direkomendasikan.
It is possible to crash the Python interpreter due to stack depth limitations in Python's AST compiler.
Dimungkinkan untuk membuat interpreter Python crash karena keterbatasan kedalaman stack pada kompiler AST Python.
It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, :exc:`MemoryError` and :exc:`RecursionError` depending on the malformed input.
Ini dapat memunculkan :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, :exc:`MemoryError` dan :exc:`RecursionError` bergantung pada masukan yang salah bentuk.
Now allows bytes and set literals.
Sekarang mengizinkan literal bytes dan set.
Now supports creating empty sets with ``'set()'``.
Sekarang mendukung pembuatan himpunan *Set* kosong dengan ``'set()'``.
For string inputs, leading spaces and tabs are now stripped.
Untuk masukan string, spasi dan tab di awal kini dihapus.
Return the docstring of the given *node* (which must be a :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, or :class:`Module` node), or ``None`` if it has no docstring. If *clean* is true, clean up the docstring's indentation with :func:`inspect.cleandoc`.
Mengembalikan docstring dari *node* yang diberikan (yang harus berupa node :class:`FunctionDef`, :class:`AsyncFunctionDef`, :class:`ClassDef`, atau :class:`Module`), atau ``None`` jika tidak memiliki docstring. Jika *clean* bernilai true, bersihkan indentasi docstring dengan :func:`inspect.cleandoc`.
:class:`AsyncFunctionDef` is now supported.
:class:`AsyncFunctionDef` sekarang didukung.
Get source code segment of the *source* that generated *node*. If some location information (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`, :attr:`~ast.AST.col_offset`, or :attr:`~ast.AST.end_col_offset`) is missing, return ``None``.
Dapatkan segmen code sumber dari *source* yang menghasilkan *node*. Jika sebagian informasi lokasi (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.end_lineno`, :attr:`~ast.AST.col_offset`, atau :attr:`~ast.AST.end_col_offset`) hilang, kembalikan ``None``.
If *padded* is ``True``, the first line of a multi-line statement will be padded with spaces to match its original position.
Jika *padded* bernilai ``True``, baris pertama dari pernyataan multi-baris akan dipenuhi spasi untuk menyesuaikan posisi aslinya.
When you compile a node tree with :func:`compile`, the compiler expects :attr:`~ast.AST.lineno` and :attr:`~ast.AST.col_offset` attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at *node*.
Saat Anda mengompilasi sebuah pohon node dengan :func:`compile`, kompiler mengharapkan atribut :attr:`~ast.AST.lineno` dan :attr:`~ast.AST.col_offset` untuk setiap node yang mendukungnya. Ini cukup membosankan untuk diisi pada node yang dihasilkan, jadi helper ini menambahkan atribut-atribut tersebut secara rekursif di tempat yang belum di-set, dengan menyetelkannya ke nilai-nilai dari node induk. Ini bekerja secara rekursif mulai dari *node*.
Increment the line number and end line number of each node in the tree starting at *node* by *n*. This is useful to "move code" to a different location in a file.
Tingkatkan line number dan end line number dari setiap node dalam pohon mulai dari *node* sebesar *n*. Ini berguna untuk "move code" ke lokasi yang berbeda dalam sebuah berkas.
Copy source location (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :attr:`~ast.AST.end_lineno`, and :attr:`~ast.AST.end_col_offset`) from *old_node* to *new_node* if possible, and return *new_node*.
Copy lokasi sumber (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, :attr:`~ast.AST.end_lineno`, dan :attr:`~ast.AST.end_col_offset`) dari *old_node* ke *new_node* jika memungkinkan, dan kembalikan *new_node*.
Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` that is present on *node*.
Hasilkan sebuah tupel ``(fieldname, value)`` untuk setiap field dalam ``node._fields`` yang ada pada *node*.
Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes.
Hasilkan semua node anak langsung dari *node*, yaitu, semua field yang berupa node dan semua item dari field yang berupa list berisi node.
Recursively yield all descendant nodes in the tree starting at *node* (including *node* itself), in no specified order. This is useful if you only want to modify nodes in place and don't care about the context.
Secara rekursif hasilkan semua node turunan dalam pohon mulai dari *node* (termasuk *node* itu sendiri), tanpa urutan tertentu. Ini berguna jika Anda hanya ingin memodifikasi node di tempat dan tidak peduli tentang konteks.
A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the :meth:`visit` method.
Sebuah kelas dasar pengunjung simpul yang menelusuri pohon sintaksis abstrak dan memanggil fungsi pengunjung untuk setiap simpul yang ditemukan. Fungsi ini dapat mengembalikan sebuah nilai yang diteruskan oleh metoda :meth:`visit`.
This class is meant to be subclassed, with the subclass adding visitor methods.
Kelas ini dimaksudkan untuk diturunkan, dengan subkelas menambahkan metode-Metode pengunjung.
Visit a node. The default implementation calls the method called :samp:`self.visit_{classname}` where *classname* is the name of the node class, or :meth:`generic_visit` if that method doesn't exist.
Kunjungi sebuah simpul. Implementasi bawaan memanggil metoda bernama :samp:`self.visit_{classname}` di mana *classname* adalah nama kelas simpul, atau :meth:`generic_visit` jika metoda itu tidak ada.
This visitor calls :meth:`visit` on all children of the node.
Pengunjung ini memanggil :meth:`visit` pada semua anak dari simpul tersebut.
Note that child nodes of nodes that have a custom visitor method won't be visited unless the visitor calls :meth:`generic_visit` or visits them itself.
Perhatikan bahwa simpul anak dari simpul yang memiliki metoda pengunjung kustom tidak akan dikunjungi kecuali pengunjung memanggil :meth:`generic_visit` atau mengunjunginya sendiri.
Handles all constant nodes.
Menangani semua simpul konstanta.
Don't use the :class:`NodeVisitor` if you want to apply changes to nodes during traversal. For this a special visitor exists (:class:`NodeTransformer`) that allows modifications.
Jangan gunakan kelas :class:`NodeVisitor` jika Anda ingin menerapkan perubahan pada simpul selama penelusuran. Untuk ini ada pengunjung khusus (:class:`NodeTransformer`) yang memungkinkan modifikasi.
Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, :meth:`!visit_NameConstant` and :meth:`!visit_Ellipsis` will not be called in Python 3.14+. Add the :meth:`visit_Constant` method instead to handle all constant nodes.
Metode-Metode :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, :meth:`!visit_NameConstant` dan :meth:`!visit_Ellipsis` tidak akan dipanggil di Python 3.14+. add metoda :meth:`visit_Constant` sebagai gantinya untuk menangani semua simpul konstanta.
A :class:`NodeVisitor` subclass that walks the abstract syntax tree and allows modification of nodes.
Sebuah subkelas :class:`NodeVisitor` yang menelusuri pohon sintaksis abstrak dan memungkinkan modifikasi pada simpul-simpul.
The :class:`NodeTransformer` will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is ``None``, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.
:class:`NodeTransformer` akan menelusuri ast dan menggunakan nilai balik dari metode-Metode pengunjung untuk mengganti atau menghapus simpul lama *Old*. Jika nilai balik dari metoda pengunjung adalah ``None``, simpul akan dihapus dari lokasinya, jika tidak maka diganti dengan nilai balik tersebut. Nilai balik dapat berupa simpul asli sehingga tidak ada penggantian yang terjadi.
Here is an example transformer that rewrites all occurrences of name lookups (``foo``) to ``data['foo']``::
Berikut adalah sebuah contoh transformer yang menulis ulang semua kemunculan pencarian nama (``foo``) menjadi ``data['foo']``::
class RewriteName(NodeTransformer):
def visit_Name(self, node):
return Subscript(
value=Name(id='data'),
slice=Constant(value=node.id),
ctx=node.ctx
)
class RewriteName(NodeTransformer):
def visit_Name(self, node):
return Subscript(
value=Name(id='data'),
slice=Constant(value=node.id),
ctx=node.ctx
)
Keep in mind that if the node you're operating on has child nodes you must either transform the child nodes yourself or call the :meth:`~ast.NodeVisitor.generic_visit` method for the node first.
Ingat bahwa jika simpul yang sedang Anda operasikan memiliki simpul anak, Anda harus mengubah simpul-simpul anak tersebut sendiri atau memanggil metoda :meth:`~ast.NodeVisitor.generic_visit` terlebih dahulu untuk simpul itu.
For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.
Untuk simpul yang merupakan bagian dari kumpulan pernyataan (berlaku untuk semua simpul pernyataan), pengunjung juga dapat mengembalikan sebuah list simpul alih-alih hanya satu simpul.
If :class:`NodeTransformer` introduces new nodes (that weren't part of original tree) without giving them location information (such as :attr:`~ast.AST.lineno`), :func:`fix_missing_locations` should be called with the new sub-tree to recalculate the location information::
Jika :class:`NodeTransformer` memperkenalkan simpul-simpul baru (yang bukan bagian dari pohon asli) tanpa memberikan informasi lokasi (seperti :attr:`~ast.AST.lineno`), :func:`fix_missing_locations` harus dipanggil dengan sub-pohon baru untuk menghitung ulang informasi lokasi::
tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
tree = ast.parse('foo', mode='eval')
new_tree = fix_missing_locations(RewriteName().visit(tree))
Usually you use the transformer like this::
Biasanya Anda gunakan transformer seperti ini::
node = YourTransformer().visit(node)
node = YourTransformer().visit(node)
Return a formatted dump of the tree in *node*. This is mainly useful for debugging purposes. If *annotate_fields* is true (by default), the returned string will show the names and the values for fields. If *annotate_fields* is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, *include_attributes* can be set to true.
Mengembalikan dump terformat dari pohon di *node*. Ini terutama berguna untuk tujuan debugging. Jika *annotate_fields* adalah true (bawaan), string yang dikembalikan akan menampilkan nama dan nilai untuk field. Jika *annotate_fields* adalah false, string hasil akan lebih ringkas dengan menghilangkan nama field yang tidak ambigu. Atribut seperti angka baris dan ofset kolom tidak didump secara bawaan. Jika ini diinginkan, *include_attributes* dapat di-set ke true.
If *color* is ``True``, the returned string is syntax highlighted using ANSI escape sequences. If ``False`` (the default), colored output is always disabled.
Jika *color* adalah ``True``, string yang dikembalikan disorot sintaksis menggunakan sekuens escape ANSI. Jika ``False`` (bawaan), keluaran berwarna selalu dinonaktifkan.
If *indent* is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or ``""`` will only insert newlines. ``None`` (the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If *indent* is a string (such as ``"\t"``), that string is used to indent each level.
Jika *indent* adalah bilangan bulat non-negatif atau string, maka pohon akan dicetak-rapi dengan level indent tersebut. Level indent 0, negatif, atau ``""`` hanya akan menyisipkan baris baru. ``None`` (bawaan) memilih representasi satu baris. Menggunakan indent bilangan bulat positif akan membuat inden sejumlah spasi itu per level. Jika *indent* adalah sebuah string (seperti ``"\t"``), string itu digunakan untuk menginden tiap level.
If *show_empty* is false (the default), optional empty lists and ``Load()`` values will be omitted from the output. Optional ``None`` values are always omitted.
Jika *show_empty* adalah false (bawaan), list kosong opsional dan nilai ``Load()`` akan dihilangkan dari keluaran. Nilai ``None`` opsional selalu dihilangkan.
>>> tree = ast.parse('print(None)', '?', 'eval')
>>> print(ast.dump(tree, indent=4))
Expression(
body=Call(
func=Name(id='print'),
args=[
Constant(value=None)]))
>>> print(ast.dump(tree, indent=4, show_empty=True))
Expression(
body=Call(
func=Name(id='print', ctx=Load()),
args=[
Constant(value=None)],
keywords=[]))
>>> tree = ast.parse('print(None)', '?', 'eval')
>>> print(ast.dump(tree, indent=4))
Expression(
body=Call(
func=Name(id='print'),
args=[
Constant(value=None)]))
>>> print(ast.dump(tree, indent=4, show_empty=True))
Expression(
body=Call(
func=Name(id='print', ctx=Load()),
args=[
Constant(value=None)],
keywords=[]))
Added the *indent* option.
Menambahkan opsi *indent*.
Added the *show_empty* option.
Menambahkan opsi *show_empty*.
Omit optional ``Load()`` values by default.
Abaikan nilai ``Load()`` yang opsional secara bawaan.
Added the *color* parameter.
Menambahkan parameter *color*.
Recursively compares two ASTs.
Membandingkan dua AST secara rekursif.
*compare_attributes* affects whether AST attributes are considered in the comparison. If *compare_attributes* is ``False`` (default), then attributes are ignored. Otherwise they must all be equal. This option is useful to check whether the ASTs are structurally equal but differ in whitespace or similar details. Attributes include line numbers and column offsets.
*compare_attributes* memengaruhi apakah atribut AST dipertimbangkan dalam perbandingan. Jika *compare_attributes* adalah ``False`` (bawaan), maka atribut diabaikan. Jika tidak, semuanya harus sama. Opsi ini berguna untuk memeriksa apakah AST secara struktural sama tapi berbeda dalam spasi atau detail serupa. Atribut mencakup angka baris dan ofset kolom.
Compiler flags
Flag kompiler
The following flags may be passed to :func:`compile` in order to change effects on the compilation of a program:
Flag berikut dapat diteruskan ke :func:`compile` untuk mengubah efek pada kompilasi sebuah program:
Enables support for top-level ``await``, ``async for``, ``async with`` and async comprehensions.
Mengaktifkan dukungan untuk ``await`` tingkat atas, ``async for``, ``async with`` dan komprehensi async.
Generates and returns an abstract syntax tree instead of returning a compiled code object.
Menghasilkan dan mengembalikan sebuah pohon sintaksis abstrak alih-alih mengembalikan objek kode terkompilasi.
The returned AST is optimized according to the *optimize* argument in :func:`compile` or :func:`ast.parse`.
AST yang dikembalikan dioptimalkan sesuai dengan argumen *optimize* di :func:`compile` atau :func:`ast.parse`.
Enables support for :pep:`484` and :pep:`526` style type comments (``# type: <type>``, ``# type: ignore <stuff>``).
Mengaktifkan dukungan untuk komentar tipe gaya :pep:`484` dan :pep:`526` (``# type: <type>``, ``# type: ignore <stuff>``).
Command-line usage
Penggunaan baris perintah
The output is now syntax highlighted by default. This can be :ref:`controlled using environment variables <using-on-controlling-color>`.
Keluaran kini memiliki penyorotan sintaksis secara bawaan. Ini dapat :ref:`dikendalikan menggunakan variabel lingkungan <using-on-controlling-color>`.
The :mod:`!ast` module can be executed as a script from the command line. It is as simple as:
Modul :mod:`!ast` dapat dieksekusi sebagai skrip dari baris perintah. Sesederhana:
python -m ast [-m <mode>] [-a] [infile]
python -m ast [-m <mode>] [-a] [infile]
The following options are accepted:
Opsi berikut diterima:
Show the help message and exit.
Tampilkan pesan help dan exit.
Specify what kind of code must be compiled, like the *mode* argument in :func:`parse`.
Tentukan jenis code yang harus dikompilasi, seperti argumen *mode* di :func:`parse`.
Don't parse type comments.
Jangan mengurai komentar tipe.
Include attributes such as line numbers and column offsets.
Sertakan atribut seperti angka baris dan ofset kolom.
Indentation of nodes in AST (number of spaces).
Indentasi node dalam AST (number of spasi).
Python version in the format 3.x (for example, 3.10). Defaults to the current version of the interpreter.
Versi Python dalam format 3.x (sebagai contoh, 3.10). Bawaannya adalah versi interpreter saat ini.
Optimization level for parser. Defaults to no optimization.
Level optimisasi untuk parser. Bawaannya tanpa optimisasi.
Show empty lists and fields that are ``None``. Defaults to not showing empty objects.
Tampilkan list kosong dan field yang ``None``. Bawaannya adalah tidak menampilkan objek kosong.
If :file:`infile` is specified its contents are parsed to AST and dumped to stdout. Otherwise, the content is read from stdin.
Jika :file:`infile` ditentukan, kontennya diurai menjadi AST dan dibuang ke stdout. Jika tidak, konten dibaca dari stdin.
`Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, an external documentation resource, has good details on working with Python ASTs.
`Green Tree Snakes <https://greentreesnakes.readthedocs.io/>`_, sebuah sumber Daya, *Resource* dokumentasi eksternal, memiliki detail yang bagus tentang bekerja dengan AST Python.
`ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_ annotates Python ASTs with the positions of tokens and text in the source code that generated them. This is helpful for tools that make source code transformations.
`ASTTokens <https://asttokens.readthedocs.io/en/latest/user-guide.html>`_ menganotasi AST Python dengan posisi token dan teks dalam code sumber yang menghasilkannya. Ini berguna untuk alat yang melakukan transformasi code sumber.
`leoAst.py <https://leo-editor.github.io/leo-editor/appendices.html#leoast-py>`_ unifies the token-based and parse-tree-based views of python programs by inserting two-way links between tokens and ast nodes.
`leoAst.py <https://leo-editor.github.io/leo-editor/appendices.html#leoast-py>`_ menyatukan tampilan berbasis token dan berbasis pohon parse dari program python dengan menyisipkan tautan dua arah antara token dan node ast.
`LibCST <https://libcst.readthedocs.io/>`_ parses code as a Concrete Syntax Tree that looks like an ast tree and keeps all formatting details. It's useful for building automated refactoring (codemod) applications and linters.
`LibCST <https://libcst.readthedocs.io/>`_ mengurai code sebagai Pohon Sintaksis Konkret yang terlihat seperti pohon ast dan mempertahankan semua detail pemformatan. Ini berguna untuk membangun aplikasi refactoring otomatis (codemod) dan linter.
`Parso <https://parso.readthedocs.io>`_ is a Python parser that supports error recovery and round-trip parsing for different Python versions (in multiple Python versions). Parso is also able to list multiple syntax errors in your Python file.
`Parso <https://parso.readthedocs.io>`_ adalah parser Python yang mendukung pemulihan kesalahan dan parsing bolak-balik untuk berbagai versi Python (dalam berbagai versi Python). Parso juga dapat melist beberapa kesalahan sintaksis dalam file Python Anda.
? (question mark)
? (question mark)
in AST grammar
dalam tata bahasa ast
* (asterisk)
* (asterisk)
Select an entry in the list to start translating.