# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2025, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2025 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.12\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-07-25 16:03+0000\n" "PO-Revision-Date: 2025-07-18 19:57+0000\n" "Last-Translator: Rafael Fontenelle , 2025\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/ast.rst:2 msgid ":mod:`!ast` --- Abstract Syntax Trees" msgstr ":mod:`!ast` --- 抽象语法树" #: ../../library/ast.rst:14 msgid "**Source code:** :source:`Lib/ast.py`" msgstr "**源代码:** :source:`Lib/ast.py`" #: ../../library/ast.rst:18 msgid "" "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." msgstr "" ":mod:`ast` 模块帮助 Python 程序处理 Python 语法的抽象语法树。抽象语法或许会随着 Python " "的更新版发行而改变;该模块能够帮助理解当前语法在编程层面的样貌。" #: ../../library/ast.rst:23 msgid "" "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." msgstr "" "抽象语法树可通过将 :data:`ast.PyCF_ONLY_AST` 作为旗标传递给 :func:`compile` " "内置函数来生成,或是使用此模块中提供的 :func:`parse` 辅助函数。返回结果将是一个由许多对象构成的树,这些对象所属的类都继承自 " ":class:`ast.AST`。抽象语法树可被内置的 :func:`compile` 函数编译为一个 Python 代码对象。" #: ../../library/ast.rst:33 msgid "Abstract Grammar" msgstr "抽象文法" #: ../../library/ast.rst:35 msgid "The abstract grammar is currently defined as follows:" msgstr "抽象文法目前定义如下" #: ../../library/ast.rst:37 msgid "" "-- ASDL's 4 builtin types are:\n" "-- identifier, int, string, constant\n" "\n" "module Python\n" "{\n" " mod = Module(stmt* body, type_ignore* type_ignores)\n" " | Interactive(stmt* body)\n" " | Expression(expr body)\n" " | FunctionType(expr* argtypes, expr returns)\n" "\n" " stmt = FunctionDef(identifier name, arguments args,\n" " stmt* body, expr* decorator_list, expr? returns,\n" " string? type_comment, type_param* type_params)\n" " | AsyncFunctionDef(identifier name, arguments args,\n" " stmt* body, expr* decorator_list, expr? returns,\n" " string? type_comment, type_param* type_params)\n" "\n" " | ClassDef(identifier name,\n" " expr* bases,\n" " keyword* keywords,\n" " stmt* body,\n" " expr* decorator_list,\n" " type_param* type_params)\n" " | Return(expr? value)\n" "\n" " | Delete(expr* targets)\n" " | Assign(expr* targets, expr value, string? type_comment)\n" " | TypeAlias(expr name, type_param* type_params, expr value)\n" " | AugAssign(expr target, operator op, expr value)\n" " -- 'simple' indicates that we annotate simple name without parens\n" " | AnnAssign(expr target, expr annotation, expr? value, int simple)\n" "\n" " -- use 'orelse' because else is a keyword in target languages\n" " | For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n" " | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n" " | While(expr test, stmt* body, stmt* orelse)\n" " | If(expr test, stmt* body, stmt* orelse)\n" " | With(withitem* items, stmt* body, string? type_comment)\n" " | AsyncWith(withitem* items, stmt* body, string? type_comment)\n" "\n" " | Match(expr subject, match_case* cases)\n" "\n" " | Raise(expr? exc, expr? cause)\n" " | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\n" " | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\n" " | Assert(expr test, expr? msg)\n" "\n" " | Import(alias* names)\n" " | ImportFrom(identifier? module, alias* names, int? level)\n" "\n" " | Global(identifier* names)\n" " | Nonlocal(identifier* names)\n" " | Expr(expr value)\n" " | Pass | Break | Continue\n" "\n" " -- col_offset is the byte offset in the utf8 string the parser uses\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " -- BoolOp() can use left & right?\n" " expr = BoolOp(boolop op, expr* values)\n" " | NamedExpr(expr target, expr value)\n" " | BinOp(expr left, operator op, expr right)\n" " | UnaryOp(unaryop op, expr operand)\n" " | Lambda(arguments args, expr body)\n" " | IfExp(expr test, expr body, expr orelse)\n" " | Dict(expr* keys, expr* values)\n" " | Set(expr* elts)\n" " | ListComp(expr elt, comprehension* generators)\n" " | SetComp(expr elt, comprehension* generators)\n" " | DictComp(expr key, expr value, comprehension* generators)\n" " | GeneratorExp(expr elt, comprehension* generators)\n" " -- the grammar constrains where yield expressions can occur\n" " | Await(expr value)\n" " | Yield(expr? value)\n" " | YieldFrom(expr value)\n" " -- need sequences for compare to distinguish between\n" " -- x < 4 < 3 and (x < 4) < 3\n" " | Compare(expr left, cmpop* ops, expr* comparators)\n" " | Call(expr func, expr* args, keyword* keywords)\n" " | FormattedValue(expr value, int conversion, expr? format_spec)\n" " | JoinedStr(expr* values)\n" " | Constant(constant value, string? kind)\n" "\n" " -- the following expression can appear in assignment context\n" " | Attribute(expr value, identifier attr, expr_context ctx)\n" " | Subscript(expr value, expr slice, expr_context ctx)\n" " | Starred(expr value, expr_context ctx)\n" " | Name(identifier id, expr_context ctx)\n" " | List(expr* elts, expr_context ctx)\n" " | Tuple(expr* elts, expr_context ctx)\n" "\n" " -- can appear only in Subscript\n" " | Slice(expr? lower, expr? upper, expr? step)\n" "\n" " -- col_offset is the byte offset in the utf8 string the parser uses\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " expr_context = Load | Store | Del\n" "\n" " boolop = And | Or\n" "\n" " operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift\n" " | RShift | BitOr | BitXor | BitAnd | FloorDiv\n" "\n" " unaryop = Invert | Not | UAdd | USub\n" "\n" " cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn\n" "\n" " comprehension = (expr target, expr iter, expr* ifs, int is_async)\n" "\n" " excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body)\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " arguments = (arg* posonlyargs, arg* args, arg? vararg, arg* kwonlyargs,\n" " expr* kw_defaults, arg? kwarg, expr* defaults)\n" "\n" " arg = (identifier arg, expr? annotation, string? type_comment)\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " -- keyword arguments supplied to call (NULL identifier for **kwargs)\n" " keyword = (identifier? arg, expr value)\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " -- import name with optional 'as' alias.\n" " alias = (identifier name, identifier? asname)\n" " attributes (int lineno, int col_offset, int? end_lineno, int? end_col_offset)\n" "\n" " withitem = (expr context_expr, expr? optional_vars)\n" "\n" " match_case = (pattern pattern, expr? guard, stmt* body)\n" "\n" " pattern = MatchValue(expr value)\n" " | MatchSingleton(constant value)\n" " | MatchSequence(pattern* patterns)\n" " | MatchMapping(expr* keys, pattern* patterns, identifier? rest)\n" " | MatchClass(expr cls, pattern* patterns, identifier* kwd_attrs, pattern* kwd_patterns)\n" "\n" " | MatchStar(identifier? name)\n" " -- The optional \"rest\" MatchMapping parameter handles capturing extra mapping keys\n" "\n" " | MatchAs(pattern? pattern, identifier? name)\n" " | MatchOr(pattern* patterns)\n" "\n" " attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)\n" "\n" " type_ignore = TypeIgnore(int lineno, string tag)\n" "\n" " type_param = TypeVar(identifier name, expr? bound)\n" " | ParamSpec(identifier name)\n" " | TypeVarTuple(identifier name)\n" " attributes (int lineno, int col_offset, int end_lineno, int end_col_offset)\n" "}\n" msgstr "" #: ../../library/ast.rst:42 msgid "Node classes" msgstr "节点类" #: ../../library/ast.rst:46 msgid "" "This is the base of all AST node classes. The actual node classes are " "derived from the :file:`Parser/Python.asdl` file, which is reproduced " ":ref:`above `. They are defined in the :mod:`!_ast` C " "module and re-exported in :mod:`ast`." msgstr "" "这是所有 AST 节点类的基类。 实际的节点类都派生自 :file:`Parser/Python.asdl` 文件,其完整内容 :ref:`如上所示 " "`。 它们 :mod:`!_ast` C 模块中定义并在 :mod:`ast` 中重新导出。" #: ../../library/ast.rst:51 msgid "" "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." msgstr "" "抽象文法中的每个等号左边的符号(比方说, :class:`ast.stmt` 或者 " ":class:`ast.expr`)定义了一个类。另外,在等号右边,对每一个构造器也定义了一个类;这些类继承自等号左边的类。比如,:class:`ast.BinOp`" " 继承自 :class:`ast.expr`。对于多分支产生式(也就是含有“ | ”的产生式),左边的类是抽象的;只有具体构造器类的实例能够被 " "compile 函数构造。" #: ../../library/ast.rst:64 msgid "" "Each concrete class has an attribute :attr:`_fields` which gives the names " "of all child nodes." msgstr "每个具体类都有属性 :attr:`_fields`,用来给出所有子节点的名字。" #: ../../library/ast.rst:67 msgid "" "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`." msgstr "" "每个具体类的实例为自己的每个子节点都准备了一个属性来引用该子节点,属性的类型就是文法中所定义的。比如,:class:`ast.BinOp` " "的实例有个属性 :attr:`left`,类型是 :class:`ast.expr`。" #: ../../library/ast.rst:71 msgid "" "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`." msgstr "" "如果这些属性在文法中标记为可选(用问号标记),对应值可能会是 " "``None``。如果这些属性可有零或多个值(用星号标记),对应值会用Python的列表来表示。在用 :func:`compile` " "将AST编译为可执行代码时,所有的属性必须已经被赋值为有效的值。" #: ../../library/ast.rst:82 msgid "" "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." msgstr "" ":class:`ast.expr` 和 :class:`ast.stmt` 的子类的实例的属性包括 " ":attr:`lineno`、:attr:`col_offset`、:attr:`end_lineno` 和 " ":attr:`end_col_offset`。:attr:`lineno` 和 :attr:`end_lineno` " "是源码中属于该节点的部分从哪一行开始,到哪一行结束(数字 1 指第一行,以此类推);:attr:`col_offset` 和 " ":attr:`end_col_offset` 是第一个和最后一个属于该节点的 token 的 UTF-8 字节偏移量。记录 UTF-8 " "偏移量的原因是解析器内部使用 UTF-8。" #: ../../library/ast.rst:91 msgid "" "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]``." msgstr "" "注意编译器不需要结束位置,所以结束位置是可选的。结束偏移在最后一个符号 *之后* ,例如你可以通过 " "``source_line[node.col_offset : node.end_col_offset]`` 获得一个单行表达式节点的源码片段。" #: ../../library/ast.rst:96 msgid "" "The constructor of a class :class:`ast.T` parses its arguments as follows:" msgstr ":class:`ast.T` 类的构造器像下面这样解析它的参数:" #: ../../library/ast.rst:98 msgid "" "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." msgstr "如果只用位置参数,参数的数量必须和 :attr:`T._fields` 中的项一样多;它们会按顺序赋值到这些属性上。" #: ../../library/ast.rst:100 msgid "" "If there are keyword arguments, they will set the attributes of the same " "names to the given values." msgstr "如果有关键字参数,它们会为与其关键字同名的属性赋值。" #: ../../library/ast.rst:103 msgid "" "For example, to create and populate an :class:`ast.UnaryOp` node, you could " "use ::" msgstr "比方说,要创建和填充节点 :class:`ast.UnaryOp`,你得用 ::" #: ../../library/ast.rst:106 msgid "" "node = ast.UnaryOp()\n" "node.op = ast.USub()\n" "node.operand = ast.Constant()\n" "node.operand.value = 5\n" "node.operand.lineno = 0\n" "node.operand.col_offset = 0\n" "node.lineno = 0\n" "node.col_offset = 0" msgstr "" #: ../../library/ast.rst:115 msgid "or the more compact ::" msgstr "或者更紧凑点 ::" #: ../../library/ast.rst:117 msgid "" "node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),\n" " lineno=0, col_offset=0)" msgstr "" "node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno=0, col_offset=0),\n" " lineno=0, col_offset=0)" #: ../../library/ast.rst:122 msgid "Class :class:`ast.Constant` is now used for all constants." msgstr ":class:`ast.Constant` 类现在用于所有常量。" #: ../../library/ast.rst:126 msgid "" "Simple indices are represented by their value, extended slices are " "represented as tuples." msgstr "简单索引由它们的值表示,扩展切片表示为元组。" #: ../../library/ast.rst:131 msgid "" "Old classes :class:`!ast.Num`, :class:`!ast.Str`, :class:`!ast.Bytes`, " ":class:`!ast.NameConstant` and :class:`!ast.Ellipsis` 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." msgstr "" "原有的类 :class:`!ast.Num`, :class:`!ast.Str`, :class:`!ast.Bytes`, " ":class:`!ast.NameConstant` 和 :class:`!ast.Ellipsis` 仍然可用,但它们将在未来的 Python " "发布版中被移除。 同时,实例化它们将返回其他某个类的实例。" #: ../../library/ast.rst:138 msgid "" "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." msgstr "" "原有的类 :class:`!ast.Index` and :class:`!ast.ExtSlice` 仍然可用,但它们将在未来的 Python " "发布版中被移除。 同时,实例化它们将返回其他某个类的实例。" #: ../../library/ast.rst:144 msgid "" "The descriptions of the specific node classes displayed here were initially " "adapted from the fantastic `Green Tree Snakes " "`__ project and all its " "contributors." msgstr "" "在此显示的特定节点类的描述最初是改编自杰出的 `Green Tree Snakes " "`__ 项目及其所有贡献者。" #: ../../library/ast.rst:153 msgid "Root nodes" msgstr "根节点" #: ../../library/ast.rst:157 msgid "" "A Python module, as with :ref:`file input `. Node type generated" " by :func:`ast.parse` in the default ``\"exec\"`` *mode*." msgstr "" "一个 Python 模块,用于 :ref:`文件输入 `。 由 :func:`ast.parse` 以默认 " "``\"exec\"`` *mode* 生成的节点类型。" #: ../../library/ast.rst:160 msgid "``body`` is a :class:`list` of the module's :ref:`ast-statements`." msgstr "``body`` 是由该模块的 :ref:`ast-statements` 组成的 :class:`list`。" #: ../../library/ast.rst:162 msgid "" "``type_ignores`` is a :class:`list` of the module's type ignore comments; " "see :func:`ast.parse` for more details." msgstr "" "``type_ignores`` 是由该模块的类型忽略注释组成的 :class:`list`;请参阅 :func:`ast.parse` 了解详情。" #: ../../library/ast.rst:165 msgid "" ">>> print(ast.dump(ast.parse('x = 1'), indent=4))\n" "Module(\n" " body=[\n" " Assign(\n" " targets=[\n" " Name(id='x', ctx=Store())],\n" " value=Constant(value=1))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:179 msgid "" "A single Python :ref:`expression input `. Node type " "generated by :func:`ast.parse` when *mode* is ``\"eval\"``." msgstr "" "单个 Python :ref:`表达式输入 `。 当 *mode* 为 ``\"eval\"`` 时由 " ":func:`ast.parse` 所生成的节点类型。" #: ../../library/ast.rst:182 msgid "" "``body`` is a single node, one of the :ref:`expression types `." msgstr "``body`` 为单独节点,是某一个 :ref:`表达式类型 `。" #: ../../library/ast.rst:185 ../../library/ast.rst:255 msgid "" ">>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))\n" "Expression(\n" " body=Constant(value=123))" msgstr "" ">>> print(ast.dump(ast.parse('123', mode='eval'), indent=4))\n" "Expression(\n" " body=Constant(value=123))" #: ../../library/ast.rst:194 msgid "" "A single :ref:`interactive input `, like in :ref:`tut-interac`." " Node type generated by :func:`ast.parse` when *mode* is ``\"single\"``." msgstr "" "单个 :ref:`交互式输入 `,就像在 :ref:`tut-interac` 中一样。 当 *mode* 为 " "``\"single\"`` 时由 :func:`ast.parse` 所生成的节点类型。" #: ../../library/ast.rst:197 msgid "" "``body`` is a :class:`list` of :ref:`statement nodes `." msgstr "``body`` 是由 :ref:`语句节点 ` 组成的 :class:`list`。" #: ../../library/ast.rst:199 msgid "" ">>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))\n" "Interactive(\n" " body=[\n" " Assign(\n" " targets=[\n" " Name(id='x', ctx=Store())],\n" " value=Constant(value=1)),\n" " Assign(\n" " targets=[\n" " Name(id='y', ctx=Store())],\n" " value=Constant(value=2))])" msgstr "" ">>> print(ast.dump(ast.parse('x = 1; y = 2', mode='single'), indent=4))\n" "Interactive(\n" " body=[\n" " Assign(\n" " targets=[\n" " Name(id='x', ctx=Store())],\n" " value=Constant(value=1)),\n" " Assign(\n" " targets=[\n" " Name(id='y', ctx=Store())],\n" " value=Constant(value=2))])" #: ../../library/ast.rst:216 msgid "" "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\"``." msgstr "" "函数的旧风格类型注释表示形式,因为 Python 3.5 之前的版本不支持 :pep:`484` 标注。 当 *mode* 为 " "``\"func_type\"`` 时由 :func:`ast.parse` 所生成的节点类型。" #: ../../library/ast.rst:220 msgid "Such type comments would look like this::" msgstr "此种类型注释的形式是这样的::" #: ../../library/ast.rst:222 msgid "" "def sum_two_number(a, b):\n" " # type: (int, int) -> int\n" " return a + b" msgstr "" "def sum_two_number(a, b):\n" " # type: (int, int) -> int\n" " return a + b" #: ../../library/ast.rst:226 msgid "" "``argtypes`` is a :class:`list` of :ref:`expression nodes `." msgstr "``argtypes`` 是由 :ref:`表达式节点 ` 组成的 :class:`list`。" #: ../../library/ast.rst:228 msgid "``returns`` is a single :ref:`expression node `." msgstr "``returns`` 是单独的 :ref:`表达式节点 `。" #: ../../library/ast.rst:230 msgid "" ">>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))\n" "FunctionType(\n" " argtypes=[\n" " Name(id='int', ctx=Load()),\n" " Name(id='str', ctx=Load())],\n" " returns=Subscript(\n" " value=Name(id='List', ctx=Load()),\n" " slice=Name(id='int', ctx=Load()),\n" " ctx=Load()))" msgstr "" ">>> print(ast.dump(ast.parse('(int, str) -> List[int]', mode='func_type'), indent=4))\n" "FunctionType(\n" " argtypes=[\n" " Name(id='int', ctx=Load()),\n" " Name(id='str', ctx=Load())],\n" " returns=Subscript(\n" " value=Name(id='List', ctx=Load()),\n" " slice=Name(id='int', ctx=Load()),\n" " ctx=Load()))" #: ../../library/ast.rst:246 msgid "Literals" msgstr "字面值" #: ../../library/ast.rst:250 msgid "" "A constant value. The ``value`` attribute of the ``Constant`` literal " "contains the Python object it represents. The values represented can be " "simple types such as a number, string or ``None``, but also immutable " "container types (tuples and frozensets) if all of their elements are " "constant." msgstr "" "一个常量。 ``Constant`` 字面值的 ``value`` 属性即为其代表的 Python 对象。它可以代表简单的数字,字符串或者 " "``None`` 对象,但是也可以代表所有元素都是常量的不可变容器(例如元组或冻结集合)。" #: ../../library/ast.rst:264 msgid "" "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`." msgstr "" "节点是以一个 f-字符串形式的格式化字段来代表的。 如果该字符串只包含单个格式化字段而没有任何其他内容则节点可以被隔离,否则它将在 " ":class:`JoinedStr` 中出现。" #: ../../library/ast.rst:268 msgid "" "``value`` is any expression node (such as a literal, a variable, or a " "function call)." msgstr "``value`` 为任意的表达式节点(如一个字面值、变量或函数调用)。" #: ../../library/ast.rst:270 msgid "``conversion`` is an integer:" msgstr "``conversion`` 是一个整数:" #: ../../library/ast.rst:272 msgid "-1: no formatting" msgstr "-1: 无格式化" #: ../../library/ast.rst:273 msgid "115: ``!s`` string formatting" msgstr "115: ``!s`` 字符串格式化" #: ../../library/ast.rst:274 msgid "114: ``!r`` repr formatting" msgstr "114: ``!r`` repr 格式化" #: ../../library/ast.rst:275 msgid "97: ``!a`` ascii formatting" msgstr "97: ``!a`` ascii 格式化" #: ../../library/ast.rst:277 msgid "" "``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." msgstr "" "``format_spec`` 是一个代表值的格式化的 :class:`JoinedStr` 节点,或者如果未指定格式则为 ``None``。 " "``conversion`` 和 ``format_spec`` 可以被同时设置。" #: ../../library/ast.rst:284 msgid "" "An f-string, comprising a series of :class:`FormattedValue` and " ":class:`Constant` nodes." msgstr "一个 f-字符串,由一系列 :class:`FormattedValue` 和 :class:`Constant` 节点组成。" #: ../../library/ast.rst:287 msgid "" ">>> print(ast.dump(ast.parse('f\"sin({a}) is {sin(a):.3}\"', mode='eval'), indent=4))\n" "Expression(\n" " body=JoinedStr(\n" " values=[\n" " Constant(value='sin('),\n" " FormattedValue(\n" " value=Name(id='a', ctx=Load()),\n" " conversion=-1),\n" " Constant(value=') is '),\n" " FormattedValue(\n" " value=Call(\n" " func=Name(id='sin', ctx=Load()),\n" " args=[\n" " Name(id='a', ctx=Load())],\n" " keywords=[]),\n" " conversion=-1,\n" " format_spec=JoinedStr(\n" " values=[\n" " Constant(value='.3')]))]))" msgstr "" #: ../../library/ast.rst:313 msgid "" "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." msgstr "" "一个列表或元组。 ``elts`` 保存一个代表元素的节点的列表。 ``ctx`` 在容器为赋值的目标时 (如 ``(x,y)=something``)" " 是 :class:`Store`,否则是 :class:`Load`。" #: ../../library/ast.rst:317 msgid "" ">>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))\n" "Expression(\n" " body=List(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)],\n" " ctx=Load()))\n" ">>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))\n" "Expression(\n" " body=Tuple(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)],\n" " ctx=Load()))" msgstr "" ">>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))\n" "Expression(\n" " body=List(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)],\n" " ctx=Load()))\n" ">>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))\n" "Expression(\n" " body=Tuple(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)],\n" " ctx=Load()))" #: ../../library/ast.rst:339 msgid "A set. ``elts`` holds a list of nodes representing the set's elements." msgstr "一个集合。 ``elts`` 保存一个代表集合的元组的节点的列表。" #: ../../library/ast.rst:341 msgid "" ">>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))\n" "Expression(\n" " body=Set(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)]))" msgstr "" ">>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))\n" "Expression(\n" " body=Set(\n" " elts=[\n" " Constant(value=1),\n" " Constant(value=2),\n" " Constant(value=3)]))" #: ../../library/ast.rst:354 msgid "" "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()`)." msgstr "" "一个字典。 ``keys`` 和 ``values`` 保存分别代表键和值的节点的列表,按照匹配的顺序(即当调用 " ":code:`dictionary.keys()` 和 :code:`dictionary.values()` 时将返回的结果)。" #: ../../library/ast.rst:358 msgid "" "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``." msgstr "" "当使用字典字面值进行字典解包操作时要扩展的表达式放入 ``values`` 列表,并将 ``None`` 放入 ``keys`` 的对应位置。" #: ../../library/ast.rst:362 msgid "" ">>> print(ast.dump(ast.parse('{\"a\":1, **d}', mode='eval'), indent=4))\n" "Expression(\n" " body=Dict(\n" " keys=[\n" " Constant(value='a'),\n" " None],\n" " values=[\n" " Constant(value=1),\n" " Name(id='d', ctx=Load())]))" msgstr "" ">>> print(ast.dump(ast.parse('{\"a\":1, **d}', mode='eval'), indent=4))\n" "Expression(\n" " body=Dict(\n" " keys=[\n" " Constant(value='a'),\n" " None],\n" " values=[\n" " Constant(value=1),\n" " Name(id='d', ctx=Load())]))" #: ../../library/ast.rst:376 msgid "Variables" msgstr "变量" #: ../../library/ast.rst:380 msgid "" "A variable name. ``id`` holds the name as a string, and ``ctx`` is one of " "the following types." msgstr "一个变量名。 ``id`` 将名称保存为字符串,而 ``ctx`` 为下列类型之一。" #: ../../library/ast.rst:388 msgid "" "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." msgstr "变量引用可被用来载入一个变量的值,为其赋一个新值,或是将其删除。 变量引用会给出一个上下文来区分这几种情况。" #: ../../library/ast.rst:392 msgid "" ">>> print(ast.dump(ast.parse('a'), indent=4))\n" "Module(\n" " body=[\n" " Expr(\n" " value=Name(id='a', ctx=Load()))],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('a = 1'), indent=4))\n" "Module(\n" " body=[\n" " Assign(\n" " targets=[\n" " Name(id='a', ctx=Store())],\n" " value=Constant(value=1))],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('del a'), indent=4))\n" "Module(\n" " body=[\n" " Delete(\n" " targets=[\n" " Name(id='a', ctx=Del())])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:421 msgid "" "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``." msgstr "" "一个 ``*var`` 变量引用。 ``value`` 保存变量,通常为一个 :class:`Name` 节点。 此类型必须在构建 " ":class:`Call` 节点并传入 ``*args`` 时被使用。" #: ../../library/ast.rst:425 msgid "" ">>> print(ast.dump(ast.parse('a, *b = it'), indent=4))\n" "Module(\n" " body=[\n" " Assign(\n" " targets=[\n" " Tuple(\n" " elts=[\n" " Name(id='a', ctx=Store()),\n" " Starred(\n" " value=Name(id='b', ctx=Store()),\n" " ctx=Store())],\n" " ctx=Store())],\n" " value=Name(id='it', ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:446 msgid "Expressions" msgstr "表达式" #: ../../library/ast.rst:450 msgid "" "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." msgstr "" "当一个表达式,例如函数调用,本身作为一个语句出现并且其返回值未被使用或存储时,它会被包装在此容器中。 ``value`` 保存本节中的其他节点之一,一个" " :class:`Constant`, :class:`Name`, :class:`Lambda`, :class:`Yield` 或者 " ":class:`YieldFrom` 节点。" #: ../../library/ast.rst:455 msgid "" ">>> print(ast.dump(ast.parse('-a'), indent=4))\n" "Module(\n" " body=[\n" " Expr(\n" " value=UnaryOp(\n" " op=USub(),\n" " operand=Name(id='a', ctx=Load())))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:469 msgid "" "A unary operation. ``op`` is the operator, and ``operand`` any expression " "node." msgstr "一个单目运算。 ``op`` 是运算符,而 ``operand`` 是任意表达式节点。" #: ../../library/ast.rst:478 msgid "" "Unary operator tokens. :class:`Not` is the ``not`` keyword, :class:`Invert` " "is the ``~`` operator." msgstr "单目运算符对应的形符。 :class:`Not` 是 ``not`` 关键字,:class:`Invert` 是 ``~`` 运算符。" #: ../../library/ast.rst:481 msgid "" ">>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))\n" "Expression(\n" " body=UnaryOp(\n" " op=Not(),\n" " operand=Name(id='x', ctx=Load())))" msgstr "" ">>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))\n" "Expression(\n" " body=UnaryOp(\n" " op=Not(),\n" " operand=Name(id='x', ctx=Load())))" #: ../../library/ast.rst:492 msgid "" "A binary operation (like addition or division). ``op`` is the operator, and " "``left`` and ``right`` are any expression nodes." msgstr "一个双目运算(如相加或相减)。 ``op`` 是运算符,而 ``left`` 和 ``right`` 是任意表达式节点。" #: ../../library/ast.rst:495 msgid "" ">>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))\n" "Expression(\n" " body=BinOp(\n" " left=Name(id='x', ctx=Load()),\n" " op=Add(),\n" " right=Name(id='y', ctx=Load())))" msgstr "" ">>> print(ast.dump(ast.parse('x + y', mode='eval'), indent=4))\n" "Expression(\n" " body=BinOp(\n" " left=Name(id='x', ctx=Load()),\n" " op=Add(),\n" " right=Name(id='y', ctx=Load())))" #: ../../library/ast.rst:519 msgid "Binary operator tokens." msgstr "双目运算符对应的形符。" #: ../../library/ast.rst:524 msgid "" "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." msgstr "" "一个布尔运算,'or' 或者 'and'。 ``op`` 是 :class:`Or` 或者 :class:`And`。 ``values`` " "是参与运算的值。 具有相同运算符的连续运算,如 ``a or b or c``,会被折叠为具有多个值的单个节点。" #: ../../library/ast.rst:529 msgid "This doesn't include ``not``, which is a :class:`UnaryOp`." msgstr "这不包括 ``not``,它属于 :class:`UnaryOp`。" #: ../../library/ast.rst:531 msgid "" ">>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))\n" "Expression(\n" " body=BoolOp(\n" " op=Or(),\n" " values=[\n" " Name(id='x', ctx=Load()),\n" " Name(id='y', ctx=Load())]))" msgstr "" ">>> print(ast.dump(ast.parse('x or y', mode='eval'), indent=4))\n" "Expression(\n" " body=BoolOp(\n" " op=Or(),\n" " values=[\n" " Name(id='x', ctx=Load()),\n" " Name(id='y', ctx=Load())]))" #: ../../library/ast.rst:545 msgid "Boolean operator tokens." msgstr "布尔运算符对应的形符。" #: ../../library/ast.rst:550 msgid "" "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." msgstr "" "两个或更多值之间的比较运算。 ``left`` 是参加比较的第一个值,``ops`` 是由运算符组成的列表,而 ``comparators`` " "是由参加比较的第一个元素之后的值组成的列表。" #: ../../library/ast.rst:554 msgid "" ">>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))\n" "Expression(\n" " body=Compare(\n" " left=Constant(value=1),\n" " ops=[\n" " LtE(),\n" " Lt()],\n" " comparators=[\n" " Name(id='a', ctx=Load()),\n" " Constant(value=10)]))" msgstr "" ">>> print(ast.dump(ast.parse('1 <= a < 10', mode='eval'), indent=4))\n" "Expression(\n" " body=Compare(\n" " left=Constant(value=1),\n" " ops=[\n" " LtE(),\n" " Lt()],\n" " comparators=[\n" " Name(id='a', ctx=Load()),\n" " Constant(value=10)]))" #: ../../library/ast.rst:579 msgid "Comparison operator tokens." msgstr "比较运算符对应的形符。" #: ../../library/ast.rst:584 msgid "" "A function call. ``func`` is the function, which will often be a " ":class:`Name` or :class:`Attribute` object. Of the arguments:" msgstr "" "一个函数调用。 ``func`` 是函数,它通常是一个 :class:`Name` 或 :class:`Attribute` 对象。 对于其参数:" #: ../../library/ast.rst:587 msgid "``args`` holds a list of the arguments passed by position." msgstr "``args`` 保存由按位置传入的参数组成的列表。" #: ../../library/ast.rst:588 msgid "" "``keywords`` holds a list of :class:`.keyword` objects representing " "arguments passed by keyword." msgstr "``keywords`` 保存了一个代表以关键字传入的参数的 :class:`.keyword` 对象的列表。" #: ../../library/ast.rst:591 msgid "" "When creating a ``Call`` node, ``args`` and ``keywords`` are required, but " "they can be empty lists." msgstr "当创建 ``Call`` 节点时,需要有 ``args`` 和 ``keywords``,但它们可以为空列表。" #: ../../library/ast.rst:594 msgid "" ">>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))\n" "Expression(\n" " body=Call(\n" " func=Name(id='func', ctx=Load()),\n" " args=[\n" " Name(id='a', ctx=Load()),\n" " Starred(\n" " value=Name(id='d', ctx=Load()),\n" " ctx=Load())],\n" " keywords=[\n" " keyword(\n" " arg='b',\n" " value=Name(id='c', ctx=Load())),\n" " keyword(\n" " value=Name(id='e', ctx=Load()))]))" msgstr "" ">>> print(ast.dump(ast.parse('func(a, b=c, *d, **e)', mode='eval'), indent=4))\n" "Expression(\n" " body=Call(\n" " func=Name(id='func', ctx=Load()),\n" " args=[\n" " Name(id='a', ctx=Load()),\n" " Starred(\n" " value=Name(id='d', ctx=Load()),\n" " ctx=Load())],\n" " keywords=[\n" " keyword(\n" " arg='b',\n" " value=Name(id='c', ctx=Load())),\n" " keyword(\n" " value=Name(id='e', ctx=Load()))]))" #: ../../library/ast.rst:615 msgid "" "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." msgstr "传给函数调用或类定义的关键字参数。 ``arg`` 是形参名称对应的原始字符串,``value`` 是要传入的节点。" #: ../../library/ast.rst:621 msgid "" "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." msgstr "" "一个表达式例如 ``a if b else c``。 每个字段保存一个单独节点,因而在下面的示例中,三个节点均为 :class:`Name` 节点。" #: ../../library/ast.rst:624 msgid "" ">>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))\n" "Expression(\n" " body=IfExp(\n" " test=Name(id='b', ctx=Load()),\n" " body=Name(id='a', ctx=Load()),\n" " orelse=Name(id='c', ctx=Load())))" msgstr "" ">>> print(ast.dump(ast.parse('a if b else c', mode='eval'), indent=4))\n" "Expression(\n" " body=IfExp(\n" " test=Name(id='b', ctx=Load()),\n" " body=Name(id='a', ctx=Load()),\n" " orelse=Name(id='c', ctx=Load())))" #: ../../library/ast.rst:636 msgid "" "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." msgstr "" "属性访问,例如 ``d.keys``。 ``value`` 是一个节点,通常为 :class:`Name`。 ``attr`` " "是一个给出属性名称的纯字符串,而 ``ctx`` 根据属性操作的方式可以为 :class:`Load`, :class:`Store` 或 " ":class:`Del`。" #: ../../library/ast.rst:641 msgid "" ">>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))\n" "Expression(\n" " body=Attribute(\n" " value=Name(id='snake', ctx=Load()),\n" " attr='colour',\n" " ctx=Load()))" msgstr "" ">>> print(ast.dump(ast.parse('snake.colour', mode='eval'), indent=4))\n" "Expression(\n" " body=Attribute(\n" " value=Name(id='snake', ctx=Load()),\n" " attr='colour',\n" " ctx=Load()))" #: ../../library/ast.rst:653 msgid "" "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." msgstr "" "一个带名称的表达式。 此 AST 节点是由赋值表达式运算符(或称海象运算符)产生的。 与第一个参数可以有多个节点的 :class:`Assign` " "节点不同,在此情况下 ``target`` 和 ``value`` 都必须为单独节点。" #: ../../library/ast.rst:658 msgid "" ">>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))\n" "Expression(\n" " body=NamedExpr(\n" " target=Name(id='x', ctx=Store()),\n" " value=Constant(value=4)))" msgstr "" ">>> print(ast.dump(ast.parse('(x := 4)', mode='eval'), indent=4))\n" "Expression(\n" " body=NamedExpr(\n" " target=Name(id='x', ctx=Store()),\n" " value=Constant(value=4)))" #: ../../library/ast.rst:669 msgid "Subscripting" msgstr "抽取" #: ../../library/ast.rst:673 msgid "" "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." msgstr "" "抽取操作,如 ``l[1]``。 ``value`` 是被抽取的对象(通常为序列或映射)。 ``slice`` 是索引号、切片或键。 它可以是一个包含 " ":class:`Slice` 的 :class:`Tuple`。 ``ctx`` 根据抽取所执行的操作可以为 :class:`Load`, " ":class:`Store` 或 :class:`Del`。" #: ../../library/ast.rst:679 msgid "" ">>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))\n" "Expression(\n" " body=Subscript(\n" " value=Name(id='l', ctx=Load()),\n" " slice=Tuple(\n" " elts=[\n" " Slice(\n" " lower=Constant(value=1),\n" " upper=Constant(value=2)),\n" " Constant(value=3)],\n" " ctx=Load()),\n" " ctx=Load()))" msgstr "" ">>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))\n" "Expression(\n" " body=Subscript(\n" " value=Name(id='l', ctx=Load()),\n" " slice=Tuple(\n" " elts=[\n" " Slice(\n" " lower=Constant(value=1),\n" " upper=Constant(value=2)),\n" " Constant(value=3)],\n" " ctx=Load()),\n" " ctx=Load()))" #: ../../library/ast.rst:697 msgid "" "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`." msgstr "" "常规切片 (形式如 ``lower:upper`` 或 ``lower:upper:step``)。 只能在 :class:`Subscript` 的 " "*slice* 字段内部出现,可以是直接切片对象或是作为 :class:`Tuple` 的元素。" #: ../../library/ast.rst:701 msgid "" ">>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))\n" "Expression(\n" " body=Subscript(\n" " value=Name(id='l', ctx=Load()),\n" " slice=Slice(\n" " lower=Constant(value=1),\n" " upper=Constant(value=2)),\n" " ctx=Load()))" msgstr "" ">>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))\n" "Expression(\n" " body=Subscript(\n" " value=Name(id='l', ctx=Load()),\n" " slice=Slice(\n" " lower=Constant(value=1),\n" " upper=Constant(value=2)),\n" " ctx=Load()))" #: ../../library/ast.rst:714 msgid "Comprehensions" msgstr "推导式" #: ../../library/ast.rst:721 msgid "" "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." msgstr "" "列表和集合推导式、生成器表达式以及字典推导式。 ``elt`` (或 ``key`` 和 ``value``) " "是一个代表将针对每个条目被求值的部分的单独节点。" #: ../../library/ast.rst:725 msgid "``generators`` is a list of :class:`comprehension` nodes." msgstr "``generators`` 是一个由 :class:`comprehension` 节点组成的列表。" #: ../../library/ast.rst:727 msgid "" ">>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))\n" "Expression(\n" " body=ListComp(\n" " elt=Name(id='x', ctx=Load()),\n" " generators=[\n" " comprehension(\n" " target=Name(id='x', ctx=Store()),\n" " iter=Name(id='numbers', ctx=Load()),\n" " ifs=[],\n" " is_async=0)]))\n" ">>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))\n" "Expression(\n" " body=DictComp(\n" " key=Name(id='x', ctx=Load()),\n" " value=BinOp(\n" " left=Name(id='x', ctx=Load()),\n" " op=Pow(),\n" " right=Constant(value=2)),\n" " generators=[\n" " comprehension(\n" " target=Name(id='x', ctx=Store()),\n" " iter=Name(id='numbers', ctx=Load()),\n" " ifs=[],\n" " is_async=0)]))\n" ">>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))\n" "Expression(\n" " body=SetComp(\n" " elt=Name(id='x', ctx=Load()),\n" " generators=[\n" " comprehension(\n" " target=Name(id='x', ctx=Store()),\n" " iter=Name(id='numbers', ctx=Load()),\n" " ifs=[],\n" " is_async=0)]))" msgstr "" #: ../../library/ast.rst:767 msgid "" "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``." msgstr "" "推导式中的一个 ``for`` 子句。 ``target`` 是针对每个元素使用的引用 —— 通常为一个 :class:`Name` 或 " ":class:`Tuple` 节点。 ``iter`` 是要执行迭代的对象。 ``ifs`` 是一个由测试表达式组成的列表:每个 ``for`` " "子句都可以拥有多个 ``ifs``。" #: ../../library/ast.rst:772 msgid "" "``is_async`` indicates a comprehension is asynchronous (using an ``async " "for`` instead of ``for``). The value is an integer (0 or 1)." msgstr "" "``is_async`` 表明推导式是异步的 (使用 ``async for`` 而不是 ``for``)。 它的值是一个整数 (0 或 1)。" #: ../../library/ast.rst:775 msgid "" ">>> print(ast.dump(ast.parse('[ord(c) for line in file for c in line]', mode='eval'),\n" "... indent=4)) # Multiple comprehensions in one.\n" "Expression(\n" " body=ListComp(\n" " elt=Call(\n" " func=Name(id='ord', ctx=Load()),\n" " args=[\n" " Name(id='c', ctx=Load())],\n" " keywords=[]),\n" " generators=[\n" " comprehension(\n" " target=Name(id='line', ctx=Store()),\n" " iter=Name(id='file', ctx=Load()),\n" " ifs=[],\n" " is_async=0),\n" " comprehension(\n" " target=Name(id='c', ctx=Store()),\n" " iter=Name(id='line', ctx=Load()),\n" " ifs=[],\n" " is_async=0)]))\n" "\n" ">>> print(ast.dump(ast.parse('(n**2 for n in it if n>5 if n<10)', mode='eval'),\n" "... indent=4)) # generator comprehension\n" "Expression(\n" " body=GeneratorExp(\n" " elt=BinOp(\n" " left=Name(id='n', ctx=Load()),\n" " op=Pow(),\n" " right=Constant(value=2)),\n" " generators=[\n" " comprehension(\n" " target=Name(id='n', ctx=Store()),\n" " iter=Name(id='it', ctx=Load()),\n" " ifs=[\n" " Compare(\n" " left=Name(id='n', ctx=Load()),\n" " ops=[\n" " Gt()],\n" " comparators=[\n" " Constant(value=5)]),\n" " Compare(\n" " left=Name(id='n', ctx=Load()),\n" " ops=[\n" " Lt()],\n" " comparators=[\n" " Constant(value=10)])],\n" " is_async=0)]))\n" "\n" ">>> print(ast.dump(ast.parse('[i async for i in soc]', mode='eval'),\n" "... indent=4)) # Async comprehension\n" "Expression(\n" " body=ListComp(\n" " elt=Name(id='i', ctx=Load()),\n" " generators=[\n" " comprehension(\n" " target=Name(id='i', ctx=Store()),\n" " iter=Name(id='soc', ctx=Load()),\n" " ifs=[],\n" " is_async=1)]))" msgstr "" #: ../../library/ast.rst:841 msgid "Statements" msgstr "语句" #: ../../library/ast.rst:845 msgid "" "An assignment. ``targets`` is a list of nodes, and ``value`` is a single " "node." msgstr "一次赋值。 ``targets`` 是一个由节点组成的列表,而 ``value`` 是一个单独节点。" #: ../../library/ast.rst:847 msgid "" "Multiple nodes in ``targets`` represents assigning the same value to each. " "Unpacking is represented by putting a :class:`Tuple` or :class:`List` within" " ``targets``." msgstr "" "``targets`` 中有多个节点表示将同一个值赋给多个目标。 解包操作是通过在 ``targets`` 中放入一个 :class:`Tuple` 或" " :class:`List` 来表示的。" #: ../../library/ast.rst:853 ../../library/ast.rst:1165 #: ../../library/ast.rst:1370 ../../library/ast.rst:1895 msgid "" "``type_comment`` is an optional string with the type annotation as a " "comment." msgstr "``type_comment`` 是带有以注释表示的类型标注的可选的字符串。" #: ../../library/ast.rst:855 msgid "" ">>> print(ast.dump(ast.parse('a = b = 1'), indent=4)) # Multiple assignment\n" "Module(\n" " body=[\n" " Assign(\n" " targets=[\n" " Name(id='a', ctx=Store()),\n" " Name(id='b', ctx=Store())],\n" " value=Constant(value=1))],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('a,b = c'), indent=4)) # Unpacking\n" "Module(\n" " body=[\n" " Assign(\n" " targets=[\n" " Tuple(\n" " elts=[\n" " Name(id='a', ctx=Store()),\n" " Name(id='b', ctx=Store())],\n" " ctx=Store())],\n" " value=Name(id='c', ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:883 msgid "" "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." msgstr "" "带有类型标注的赋值。 ``target`` 是单独的节点并可以是一个 :class:`Name`, :class:`Attribute` 或 " ":class:`Subscript`。 ``annotation`` 是标注,例如一个 :class:`Constant` 或 " ":class:`Name` 节点。 ``value`` 是单独的可选节点。" #: ../../library/ast.rst:888 msgid "" "``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." msgstr "" "``simple`` 将始终为 0 (表示一个“复杂”目标) 或 1 (表示一个“简单”目标)。 “简单”目标仅由一个两边不带圆括号的 " ":class:`Name` 结点组成;所有其他目标均被视为复杂目标。 只有简单目标会出现在模块和类的 " ":attr:`~object.__annotations__` 字典中。 " #: ../../library/ast.rst:894 msgid "" ">>> print(ast.dump(ast.parse('c: int'), indent=4))\n" "Module(\n" " body=[\n" " AnnAssign(\n" " target=Name(id='c', ctx=Store()),\n" " annotation=Name(id='int', ctx=Load()),\n" " simple=1)],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('(a): int = 1'), indent=4)) # Annotation with parenthesis\n" "Module(\n" " body=[\n" " AnnAssign(\n" " target=Name(id='a', ctx=Store()),\n" " annotation=Name(id='int', ctx=Load()),\n" " value=Constant(value=1),\n" " simple=0)],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('a.b: int'), indent=4)) # Attribute annotation\n" "Module(\n" " body=[\n" " AnnAssign(\n" " target=Attribute(\n" " value=Name(id='a', ctx=Load()),\n" " attr='b',\n" " ctx=Store()),\n" " annotation=Name(id='int', ctx=Load()),\n" " simple=0)],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('a[1]: int'), indent=4)) # Subscript annotation\n" "Module(\n" " body=[\n" " AnnAssign(\n" " target=Subscript(\n" " value=Name(id='a', ctx=Load()),\n" " slice=Constant(value=1),\n" " ctx=Store()),\n" " annotation=Name(id='int', ctx=Load()),\n" " simple=0)],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:942 msgid "" "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." msgstr "" "增强赋值,如 ``a += 1``。 在下面的例子中,``target`` 是一个针对 ``x`` (带有 :class:`Store` 上下文) 的 " ":class:`Name` 节点,``op`` 为 :class:`Add`,而 ``value`` 是一个值为 1 的 " ":class:`Constant`。" #: ../../library/ast.rst:947 msgid "" "The ``target`` attribute cannot be of class :class:`Tuple` or :class:`List`," " unlike the targets of :class:`Assign`." msgstr "" "``target`` 属性不可以是 :class:`Tuple` 或 :class:`List` 类,这与 :class:`Assign` 的目标不同。" #: ../../library/ast.rst:950 msgid "" ">>> print(ast.dump(ast.parse('x += 2'), indent=4))\n" "Module(\n" " body=[\n" " AugAssign(\n" " target=Name(id='x', ctx=Store()),\n" " op=Add(),\n" " value=Constant(value=2))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:964 msgid "" "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``." msgstr "" "一条 ``raise`` 语句。 ``exc`` 是要引发的异常,对于一个单独的 ``raise`` 通常为 :class:`Call` 或 " ":class:`Name`,或者为 ``None``。 ``cause`` 是针对 ``raise x from y`` 中 ``y`` 的可选部分。" #: ../../library/ast.rst:968 msgid "" ">>> print(ast.dump(ast.parse('raise x from y'), indent=4))\n" "Module(\n" " body=[\n" " Raise(\n" " exc=Name(id='x', ctx=Load()),\n" " cause=Name(id='y', ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:981 msgid "" "An assertion. ``test`` holds the condition, such as a :class:`Compare` node." " ``msg`` holds the failure message." msgstr "一条断言。 ``test`` 保存条件,例如为一个 :class:`Compare` 节点。 ``msg`` 保存失败消息。" #: ../../library/ast.rst:984 msgid "" ">>> print(ast.dump(ast.parse('assert x,y'), indent=4))\n" "Module(\n" " body=[\n" " Assert(\n" " test=Name(id='x', ctx=Load()),\n" " msg=Name(id='y', ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:997 msgid "" "Represents a ``del`` statement. ``targets`` is a list of nodes, such as " ":class:`Name`, :class:`Attribute` or :class:`Subscript` nodes." msgstr "" "代表一条 ``del`` 语句。 ``targets`` 是一个由节点组成的列表,例如 :class:`Name`, " ":class:`Attribute` 或 :class:`Subscript` 节点。" #: ../../library/ast.rst:1000 msgid "" ">>> print(ast.dump(ast.parse('del x,y,z'), indent=4))\n" "Module(\n" " body=[\n" " Delete(\n" " targets=[\n" " Name(id='x', ctx=Del()),\n" " Name(id='y', ctx=Del()),\n" " Name(id='z', ctx=Del())])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1015 msgid "A ``pass`` statement." msgstr "一条 ``pass`` 语句。" #: ../../library/ast.rst:1017 msgid "" ">>> print(ast.dump(ast.parse('pass'), indent=4))\n" "Module(\n" " body=[\n" " Pass()],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1028 msgid "" "A :ref:`type alias ` created through the :keyword:`type` " "statement. ``name`` is the name of the alias, ``type_params`` is a list of " ":ref:`type parameters `, and ``value`` is the value of the " "type alias." msgstr "" "通过 :keyword:`type` 语句创建的 :ref:`类型别名 `。 ``name`` " "是别名的名称,``type_params`` 是 :ref:`类型形参 ` 的列表,而 ``value`` " "是类型别名的值。" #: ../../library/ast.rst:1033 msgid "" ">>> print(ast.dump(ast.parse('type Alias = int'), indent=4))\n" "Module(\n" " body=[\n" " TypeAlias(\n" " name=Name(id='Alias', ctx=Store()),\n" " type_params=[],\n" " value=Name(id='int', ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1046 msgid "" "Other statements which are only applicable inside functions or loops are " "described in other sections." msgstr "其他仅在函数或循环内部可用的语句将在其他小节中描述。" #: ../../library/ast.rst:1050 msgid "Imports" msgstr "导入" #: ../../library/ast.rst:1054 msgid "An import statement. ``names`` is a list of :class:`alias` nodes." msgstr "一条导入语句。 ``names`` 是一个由 :class:`alias` 节点组成的列表。" #: ../../library/ast.rst:1056 msgid "" ">>> print(ast.dump(ast.parse('import x,y,z'), indent=4))\n" "Module(\n" " body=[\n" " Import(\n" " names=[\n" " alias(name='x'),\n" " alias(name='y'),\n" " alias(name='z')])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1071 msgid "" "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)." msgstr "" "代表 ``from x import y``。 ``module`` 是一个 'from' 名称的原始字符串,不带任何前导点号,或者为 ``None``" " 表示 ``from . import foo`` 这样的语句。 ``level`` 是一个保存相对导入层级的整数(0 表示绝对导入)。" #: ../../library/ast.rst:1076 msgid "" ">>> print(ast.dump(ast.parse('from y import x,y,z'), indent=4))\n" "Module(\n" " body=[\n" " ImportFrom(\n" " module='y',\n" " names=[\n" " alias(name='x'),\n" " alias(name='y'),\n" " alias(name='z')],\n" " level=0)],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1093 msgid "" "Both parameters are raw strings of the names. ``asname`` can be ``None`` if " "the regular name is to be used." msgstr "两个形参均为名称的原始字符串。 如果要使用常规名称则 ``asname`` 可以为 ``None``。" #: ../../library/ast.rst:1096 msgid "" ">>> print(ast.dump(ast.parse('from ..foo.bar import a as b, c'), indent=4))\n" "Module(\n" " body=[\n" " ImportFrom(\n" " module='foo.bar',\n" " names=[\n" " alias(name='a', asname='b'),\n" " alias(name='c')],\n" " level=2)],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1110 msgid "Control flow" msgstr "控制流" #: ../../library/ast.rst:1113 msgid "" "Optional clauses such as ``else`` are stored as an empty list if they're not" " present." msgstr "可选的子句如 ``else`` 如果不存在则会被存储为一个空列表。" #: ../../library/ast.rst:1118 msgid "" "An ``if`` statement. ``test`` holds a single node, such as a " ":class:`Compare` node. ``body`` and ``orelse`` each hold a list of nodes." msgstr "" "一条 ``if`` 语句。 ``test`` 保存一个单独节点,如一个 :class:`Compare` 节点。 ``body`` 和 " "``orelse`` 各自保存一个节点列表。" #: ../../library/ast.rst:1121 msgid "" "``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." msgstr "" "``elif`` 子句在 AST 中没有特别的表示形式,而是作为上文介绍的 ``orelse`` 部分之内的一个额外 :class:`If` 节点出现。" #: ../../library/ast.rst:1125 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... if x:\n" "... ...\n" "... elif y:\n" "... ...\n" "... else:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " If(\n" " test=Name(id='x', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " orelse=[\n" " If(\n" " test=Name(id='y', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " orelse=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1156 msgid "" "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." msgstr "" "一个 ``for`` 循环。 ``target`` 保存循环赋值的变量,是一个单独的 :class:`Name`, :class:`Tuple`, " ":class:`List`, :class:`Attribute` 或 :class:`Subscript` 节点。 ``iter`` " "保存要被循环的条目,同样也是一个单独节点。 ``body`` 和 ``orelse`` 包含要执行的节点列表。 ``orelse`` " "中的语句会在循环正常结束时被执行,而不是通过 ``break`` 语句执行。" #: ../../library/ast.rst:1167 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... for x in y:\n" "... ...\n" "... else:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " For(\n" " target=Name(id='x', ctx=Store()),\n" " iter=Name(id='y', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " orelse=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1191 msgid "" "A ``while`` loop. ``test`` holds the condition, such as a :class:`Compare` " "node." msgstr "一个 ``while`` 循环。 ``test`` 保存条件,如一个 :class:`Compare` 节点。" #: ../../library/ast.rst:1194 msgid "" ">> print(ast.dump(ast.parse(\"\"\"\n" "... while x:\n" "... ...\n" "... else:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " While(\n" " test=Name(id='x', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " orelse=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1218 msgid "The ``break`` and ``continue`` statements." msgstr "``break`` 和 ``continue`` 语句。" #: ../../library/ast.rst:1220 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... for a in b:\n" "... if a > 5:\n" "... break\n" "... else:\n" "... continue\n" "...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " For(\n" " target=Name(id='a', ctx=Store()),\n" " iter=Name(id='b', ctx=Load()),\n" " body=[\n" " If(\n" " test=Compare(\n" " left=Name(id='a', ctx=Load()),\n" " ops=[\n" " Gt()],\n" " comparators=[\n" " Constant(value=5)]),\n" " body=[\n" " Break()],\n" " orelse=[\n" " Continue()])],\n" " orelse=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1253 msgid "" "``try`` blocks. All attributes are list of nodes to execute, except for " "``handlers``, which is a list of :class:`ExceptHandler` nodes." msgstr "" "``try`` 代码块。 所有属性都是要执行的节点列表,除了 ``handlers``,它是一个 :class:`ExceptHandler` " "节点列表。" #: ../../library/ast.rst:1256 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... try:\n" "... ...\n" "... except Exception:\n" "... ...\n" "... except OtherException as e:\n" "... ...\n" "... else:\n" "... ...\n" "... finally:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Try(\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " handlers=[\n" " ExceptHandler(\n" " type=Name(id='Exception', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " ExceptHandler(\n" " type=Name(id='OtherException', ctx=Load()),\n" " name='e',\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])],\n" " orelse=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " finalbody=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1299 msgid "" "``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 then ``except``." msgstr "" "``try`` 代码块后带有 ``except*`` 子句。 包含的属性与 :class:`Try` 的相同但 " ":class:`ExceptHandler` 节点在 ``handlers`` 中会被解读为 ``except*`` 而不是 ``except`` " "代码块。" #: ../../library/ast.rst:1303 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... try:\n" "... ...\n" "... except* Exception:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " TryStar(\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))],\n" " handlers=[\n" " ExceptHandler(\n" " type=Name(id='Exception', ctx=Load()),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])],\n" " orelse=[],\n" " finalbody=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1331 msgid "" "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." msgstr "" "一个单独的 ``except`` 子句。 ``type`` 是它将匹配的异常,通常为一个 :class:`Name` 节点(或 ``None`` " "表示捕获全部的 ``except:`` 子句)。 ``name`` 是一个用于存放异常的别名的原始字符串,或者如果子句没有 ``as foo`` 则为 " "``None``。 ``body`` 为一个节点列表。" #: ../../library/ast.rst:1336 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... try:\n" "... a + 1\n" "... except TypeError:\n" "... pass\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Try(\n" " body=[\n" " Expr(\n" " value=BinOp(\n" " left=Name(id='a', ctx=Load()),\n" " op=Add(),\n" " right=Constant(value=1)))],\n" " handlers=[\n" " ExceptHandler(\n" " type=Name(id='TypeError', ctx=Load()),\n" " body=[\n" " Pass()])],\n" " orelse=[],\n" " finalbody=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1365 msgid "" "A ``with`` block. ``items`` is a list of :class:`withitem` nodes " "representing the context managers, and ``body`` is the indented block inside" " the context." msgstr "" "一个 ``with`` 代码块。 ``items`` 是一个代表上下文管理器的 :class:`withitem` 节点列表,而 ``body`` " "是该上下文中的缩进代码块。" #: ../../library/ast.rst:1375 msgid "" "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." msgstr "" "一个 ``with`` 代码块中单独的上下文管理器。 ``context_expr`` 为上下文管理器,通常为一个 :class:`Call` 节点。 " "``optional_vars`` 为一个针对 ``as foo`` 部分的 :class:`Name`, :class:`Tuple` 或 " ":class:`List`,或者如果未使用别名则为 ``None``。" #: ../../library/ast.rst:1380 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... with a as b, c as d:\n" "... something(b, d)\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " With(\n" " items=[\n" " withitem(\n" " context_expr=Name(id='a', ctx=Load()),\n" " optional_vars=Name(id='b', ctx=Store())),\n" " withitem(\n" " context_expr=Name(id='c', ctx=Load()),\n" " optional_vars=Name(id='d', ctx=Store()))],\n" " body=[\n" " Expr(\n" " value=Call(\n" " func=Name(id='something', ctx=Load()),\n" " args=[\n" " Name(id='b', ctx=Load()),\n" " Name(id='d', ctx=Load())],\n" " keywords=[]))])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1408 msgid "Pattern matching" msgstr "模式匹配" #: ../../library/ast.rst:1413 msgid "" "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." msgstr "" "一条 ``match`` 语句。 ``subject`` 保存匹配的目标(与 cases 相匹配的对象)而 ``cases`` 包含一个由不同分支的 " ":class:`match_case` 节点组成的可迭代对象。" #: ../../library/ast.rst:1421 msgid "" "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." msgstr "" "一个 ``match`` 语句中单独的 case 模式。 ``pattern`` 包含目标将要去匹配的匹配模式。 请注意针对模式所产生的 " ":class:`AST` 节点不同于针对表达式所产生的节点,即使它们共享相同的语法。" #: ../../library/ast.rst:1426 msgid "" "The ``guard`` attribute contains an expression that will be evaluated if the" " pattern matches the subject." msgstr "``guard`` 属性包含一个当模式与目标相匹配时将被求值的表达式。" #: ../../library/ast.rst:1429 msgid "" "``body`` contains a list of nodes to execute if the pattern matches and the " "result of evaluating the guard expression is true." msgstr "``body`` 包含一个当模式匹配并且对 guard 表达式求值的结果为真时要执行的节点列表。" #: ../../library/ast.rst:1432 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case [x] if x>0:\n" "... ...\n" "... case tuple():\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchSequence(\n" " patterns=[\n" " MatchAs(name='x')]),\n" " guard=Compare(\n" " left=Name(id='x', ctx=Load()),\n" " ops=[\n" " Gt()],\n" " comparators=[\n" " Constant(value=0)]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " match_case(\n" " pattern=MatchClass(\n" " cls=Name(id='tuple', ctx=Load()),\n" " patterns=[],\n" " kwd_attrs=[],\n" " kwd_patterns=[]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1474 msgid "" "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." msgstr "" "一个按相等性进行比较的匹配字面值或值模式。 ``value`` 为一个表达式节点。 允许的值节点被限制为 match 语句文档中所描述的节点。 " "如果匹配目标等于 value 的求值结果则模式匹配成功。" #: ../../library/ast.rst:1479 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case \"Relevant\":\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchValue(\n" " value=Constant(value='Relevant')),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1503 msgid "" "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." msgstr "" "一个按标识号进行比较的匹配字面值模式。 ``value`` 为用于比较的单例对象: ``None``, ``True`` 或 ``False``。 " "如果匹配目标为给定的常量则该模式匹配成功。" #: ../../library/ast.rst:1507 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case None:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchSingleton(value=None),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1530 msgid "" "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." msgstr "" "一个匹配序列模式。 ``patterns`` 包含当目标为一个序列时要与目标元素进行匹配的模式。 如果某一子模式为 ``MatchStar`` " "节点则将匹配一个变长度序列,否则将匹配一个固定长度序列。" #: ../../library/ast.rst:1535 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case [1, 2]:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchSequence(\n" " patterns=[\n" " MatchValue(\n" " value=Constant(value=1)),\n" " MatchValue(\n" " value=Constant(value=2))]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1563 msgid "" "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." msgstr "" "匹配一个可变长度匹配序列模式中的剩余部分序列。 如果 ``name`` 不为 " "``None``,则当整个序列模式匹配成功时将把一个包含剩余序列元素的列表绑定到该名称。" #: ../../library/ast.rst:1567 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case [1, 2, *rest]:\n" "... ...\n" "... case [*_]:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchSequence(\n" " patterns=[\n" " MatchValue(\n" " value=Constant(value=1)),\n" " MatchValue(\n" " value=Constant(value=2)),\n" " MatchStar(name='rest')]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " match_case(\n" " pattern=MatchSequence(\n" " patterns=[\n" " MatchStar()]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1605 msgid "" "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." msgstr "" "一个匹配的映射模式。 ``keys`` 为一个由表达式节点组成的序列。 ``patterns`` 为一个由对应的模式节点组成的序列。 ``rest`` " "是一个可被指定用来捕获剩余映射元素的可选名称。 允许的关键字表达式被限制为与 match 语句文档中所描述的一致。" #: ../../library/ast.rst:1611 msgid "" "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." msgstr "" "如果目标为一个映射、所有被求值的表达式都存在于该映射中,并且对应于每个键的值都与对应的子模式相匹配则此模式匹配成功。 如果 ``rest`` 不为 " "``None``,则当整个映射模式匹配成功时会将一个包含剩余映射元素的字典绑定到该名称。" #: ../../library/ast.rst:1617 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case {1: _, 2: _}:\n" "... ...\n" "... case {**rest}:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchMapping(\n" " keys=[\n" " Constant(value=1),\n" " Constant(value=2)],\n" " patterns=[\n" " MatchAs(),\n" " MatchAs()]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " match_case(\n" " pattern=MatchMapping(keys=[], patterns=[], rest='rest'),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1653 msgid "" "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)." msgstr "" "一个 match 类模式。 ``cls`` 为一个给出要匹配的名义类的表达式。 ``patterns`` " "为一个由要与该类所定义的模式匹配属性相匹配的模式节点组成的序列。 ``kwd_attrs`` " "为一个由要匹配的附加属性(指定为该类模式中的关键字参数)组成的序列,``kwd_patterns`` 为对应的模式(指定为该类模式中的关键字值)。" #: ../../library/ast.rst:1660 msgid "" "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." msgstr "如果目标为被指名类的一个实例、所有的位置模式都与对应的类定义属性相匹配,并且任何被指定的关键字属性都与其对应的模式相匹配则此模式匹配成功。" #: ../../library/ast.rst:1664 msgid "" "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." msgstr "" "注意:类可能会定义一个返回自身的特征属性以便能将一个模式节点与被匹配的实例相匹配。 某些内置类型也是以这种方式来匹配的,与 match " "语句文档中所描述的一致。" #: ../../library/ast.rst:1668 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case Point2D(0, 0):\n" "... ...\n" "... case Point3D(x=0, y=0, z=0):\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchClass(\n" " cls=Name(id='Point2D', ctx=Load()),\n" " patterns=[\n" " MatchValue(\n" " value=Constant(value=0)),\n" " MatchValue(\n" " value=Constant(value=0))],\n" " kwd_attrs=[],\n" " kwd_patterns=[]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " match_case(\n" " pattern=MatchClass(\n" " cls=Name(id='Point3D', ctx=Load()),\n" " patterns=[],\n" " kwd_attrs=[\n" " 'x',\n" " 'y',\n" " 'z'],\n" " kwd_patterns=[\n" " MatchValue(\n" " value=Constant(value=0)),\n" " MatchValue(\n" " value=Constant(value=0)),\n" " MatchValue(\n" " value=Constant(value=0))]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1719 msgid "" "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." msgstr "" "一个匹配 \"as-模式\"、捕获模式或通配符模式。 ``pattern`` 包含将要与目标相匹配的匹配模式。 如果模式为 " "``None``,则该节点代表一个捕获模式(即一个简单的名称)并将总是会成功。" #: ../../library/ast.rst:1724 msgid "" "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." msgstr "" "``name`` 属性包含当模式匹配成功时将要绑定的名称。 如果 ``name`` 为 ``None``,则 ``pattern`` 也必须为 " "``None`` 并且该节点代表的是通配符模式。" #: ../../library/ast.rst:1728 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case [x] as y:\n" "... ...\n" "... case _:\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchAs(\n" " pattern=MatchSequence(\n" " patterns=[\n" " MatchAs(name='x')]),\n" " name='y'),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))]),\n" " match_case(\n" " pattern=MatchAs(),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1762 msgid "" "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." msgstr "" "一个匹配 \"or-模式\"。 or-模式会依次将其每个子模式与目标相匹配,直到有一个匹配成功。 此时该 or-模式将被视为匹配成功。 " "如果没有一个子模式匹配成功则该 or-模式匹配失败。 ``patterns`` 属性包含一个由将与目标相匹配的匹配模式节点组成的列表。" #: ../../library/ast.rst:1768 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\n" "... match x:\n" "... case [x] | (y):\n" "... ...\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " Match(\n" " subject=Name(id='x', ctx=Load()),\n" " cases=[\n" " match_case(\n" " pattern=MatchOr(\n" " patterns=[\n" " MatchSequence(\n" " patterns=[\n" " MatchAs(name='x')]),\n" " MatchAs(name='y')]),\n" " body=[\n" " Expr(\n" " value=Constant(value=Ellipsis))])])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1797 msgid "Type parameters" msgstr "类型形参" #: ../../library/ast.rst:1799 msgid "" ":ref:`Type parameters ` can exist on classes, functions, and " "type aliases." msgstr ":ref:`类型形参 ` 可以存在于类、函数和类型别名中。" #: ../../library/ast.rst:1804 msgid "" "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." msgstr "" "一个 :class:`typing.TypeVar`。 ``name`` 是类型变量的名称。 ``bound`` 是可能存在的边界或约束。 如果 " "``bound`` 是一个 :class:`Tuple`,它代表约束;否则它代表边界。" #: ../../library/ast.rst:1808 msgid "" ">>> print(ast.dump(ast.parse(\"type Alias[T: int] = list[T]\"), indent=4))\n" "Module(\n" " body=[\n" " TypeAlias(\n" " name=Name(id='Alias', ctx=Store()),\n" " type_params=[\n" " TypeVar(\n" " name='T',\n" " bound=Name(id='int', ctx=Load()))],\n" " value=Subscript(\n" " value=Name(id='list', ctx=Load()),\n" " slice=Name(id='T', ctx=Load()),\n" " ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1829 msgid "" "A :class:`typing.ParamSpec`. ``name`` is the name of the parameter " "specification." msgstr "一个 :class:`typing.ParamSpec`。 ``name`` 是形参规格说明的名称。" #: ../../library/ast.rst:1831 msgid "" ">>> print(ast.dump(ast.parse(\"type Alias[**P] = Callable[P, int]\"), indent=4))\n" "Module(\n" " body=[\n" " TypeAlias(\n" " name=Name(id='Alias', ctx=Store()),\n" " type_params=[\n" " ParamSpec(name='P')],\n" " value=Subscript(\n" " value=Name(id='Callable', ctx=Load()),\n" " slice=Tuple(\n" " elts=[\n" " Name(id='P', ctx=Load()),\n" " Name(id='int', ctx=Load())],\n" " ctx=Load()),\n" " ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1854 msgid "" "A :class:`typing.TypeVarTuple`. ``name`` is the name of the type variable " "tuple." msgstr "一个 :class:`typing.TypeVarTuple`。 ``name`` 是类型变量元组的名称。" #: ../../library/ast.rst:1856 msgid "" ">>> print(ast.dump(ast.parse(\"type Alias[*Ts] = tuple[*Ts]\"), indent=4))\n" "Module(\n" " body=[\n" " TypeAlias(\n" " name=Name(id='Alias', ctx=Store()),\n" " type_params=[\n" " TypeVarTuple(name='Ts')],\n" " value=Subscript(\n" " value=Name(id='tuple', ctx=Load()),\n" " slice=Tuple(\n" " elts=[\n" " Starred(\n" " value=Name(id='Ts', ctx=Load()),\n" " ctx=Load())],\n" " ctx=Load()),\n" " ctx=Load()))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1879 msgid "Function and class definitions" msgstr "函数与类定义" #: ../../library/ast.rst:1883 msgid "A function definition." msgstr "一个函数定义。" #: ../../library/ast.rst:1885 msgid "``name`` is a raw string of the function name." msgstr "``name`` 是函数名称的原始字符串。" #: ../../library/ast.rst:1886 msgid "``args`` is an :class:`arguments` node." msgstr "``args`` 是一个 :class:`arguments` 节点。" #: ../../library/ast.rst:1887 msgid "``body`` is the list of nodes inside the function." msgstr "``body`` 是函数内部的节点列表。" #: ../../library/ast.rst:1888 msgid "" "``decorator_list`` is the list of decorators to be applied, stored outermost" " first (i.e. the first in the list will be applied last)." msgstr "``decorator_list`` 是要应用的装饰器列表,最外层的最先保存(即列表中的第一项将最后被应用)。" #: ../../library/ast.rst:1890 msgid "``returns`` is the return annotation." msgstr "``returns`` 是返回标注。" #: ../../library/ast.rst:1891 ../../library/ast.rst:2067 msgid "``type_params`` is a list of :ref:`type parameters `." msgstr "``type_params`` 是一个 :ref:`类型形参 ` 的列表。" #: ../../library/ast.rst:1897 ../../library/ast.rst:2096 #: ../../library/ast.rst:2107 msgid "Added ``type_params``." msgstr "增加了 ``type_params``。" #: ../../library/ast.rst:1903 msgid "" "``lambda`` is a minimal function definition that can be used inside an " "expression. Unlike :class:`FunctionDef`, ``body`` holds a single node." msgstr "" "``lambda`` 是可在表达式内部使用的最小化函数定义。 不同于 :class:`FunctionDef`,``body`` 是保存一个单独节点。" #: ../../library/ast.rst:1906 msgid "" ">>> print(ast.dump(ast.parse('lambda x,y: ...'), indent=4))\n" "Module(\n" " body=[\n" " Expr(\n" " value=Lambda(\n" " args=arguments(\n" " posonlyargs=[],\n" " args=[\n" " arg(arg='x'),\n" " arg(arg='y')],\n" " kwonlyargs=[],\n" " kw_defaults=[],\n" " defaults=[]),\n" " body=Constant(value=Ellipsis)))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1927 msgid "The arguments for a function." msgstr "函数的参数。" #: ../../library/ast.rst:1929 msgid "" "``posonlyargs``, ``args`` and ``kwonlyargs`` are lists of :class:`arg` " "nodes." msgstr "``posonlyargs``, ``args`` 和 ``kwonlyargs`` 均为 :class:`arg` 节点的列表。" #: ../../library/ast.rst:1930 msgid "" "``vararg`` and ``kwarg`` are single :class:`arg` nodes, referring to the " "``*args, **kwargs`` parameters." msgstr "" "``vararg`` 和 ``kwarg`` 均为单独的 :class:`arg` 节点,指向 ``*args, **kwargs`` 形参。" #: ../../library/ast.rst:1932 msgid "" "``kw_defaults`` is a list of default values for keyword-only arguments. If " "one is ``None``, the corresponding argument is required." msgstr "``kw_defaults`` 是一个由仅限关键字参数默认值组成的列表。 如果有一个为 ``None``,则对应的参数为必须的参数。" #: ../../library/ast.rst:1934 msgid "" "``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." msgstr "``defaults`` 是一个由可按位置传入的参数的默认值组成的列表。 如果默认值个数少于参数个数,则它们将对应最后 n 个参数。" #: ../../library/ast.rst:1941 msgid "" "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." msgstr "" "列表中的一个单独参数。 ``arg`` 为参数名称原始字符串;``annotation`` 为其标,如一个 :class:`Name` 节点。" #: ../../library/ast.rst:1946 msgid "" "``type_comment`` is an optional string with the type annotation as a comment" msgstr "``type_comment`` 是一个可选的将注释用作类型标注的字符串。" #: ../../library/ast.rst:1948 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... @decorator1\n" "... @decorator2\n" "... def f(a: 'annotation', b=1, c=2, *d, e, f=3, **g) -> 'return annotation':\n" "... pass\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " FunctionDef(\n" " name='f',\n" " args=arguments(\n" " posonlyargs=[],\n" " args=[\n" " arg(\n" " arg='a',\n" " annotation=Constant(value='annotation')),\n" " arg(arg='b'),\n" " arg(arg='c')],\n" " vararg=arg(arg='d'),\n" " kwonlyargs=[\n" " arg(arg='e'),\n" " arg(arg='f')],\n" " kw_defaults=[\n" " None,\n" " Constant(value=3)],\n" " kwarg=arg(arg='g'),\n" " defaults=[\n" " Constant(value=1),\n" " Constant(value=2)]),\n" " body=[\n" " Pass()],\n" " decorator_list=[\n" " Name(id='decorator1', ctx=Load()),\n" " Name(id='decorator2', ctx=Load())],\n" " returns=Constant(value='return annotation'),\n" " type_params=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:1991 msgid "A ``return`` statement." msgstr "一条 ``return`` 语句。" #: ../../library/ast.rst:1993 msgid "" ">>> print(ast.dump(ast.parse('return 4'), indent=4))\n" "Module(\n" " body=[\n" " Return(\n" " value=Constant(value=4))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:2006 msgid "" "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." msgstr "" "一个 ``yield`` 或 ``yield from`` 表达式。 因为这些属性表达式,所以如果发回的值未被使用则必须将它们包装在 " ":class:`Expr` 节点中。" #: ../../library/ast.rst:2009 msgid "" ">>> print(ast.dump(ast.parse('yield x'), indent=4))\n" "Module(\n" " body=[\n" " Expr(\n" " value=Yield(\n" " value=Name(id='x', ctx=Load())))],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('yield from x'), indent=4))\n" "Module(\n" " body=[\n" " Expr(\n" " value=YieldFrom(\n" " value=Name(id='x', ctx=Load())))],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:2031 msgid "" "``global`` and ``nonlocal`` statements. ``names`` is a list of raw strings." msgstr "``global`` 和 ``nonlocal`` 语句。 ``names`` 为一个由原始字符串组成的列表。" #: ../../library/ast.rst:2033 msgid "" ">>> print(ast.dump(ast.parse('global x,y,z'), indent=4))\n" "Module(\n" " body=[\n" " Global(\n" " names=[\n" " 'x',\n" " 'y',\n" " 'z'])],\n" " type_ignores=[])\n" "\n" ">>> print(ast.dump(ast.parse('nonlocal x,y,z'), indent=4))\n" "Module(\n" " body=[\n" " Nonlocal(\n" " names=[\n" " 'x',\n" " 'y',\n" " 'z'])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:2058 msgid "A class definition." msgstr "一个类定义。" #: ../../library/ast.rst:2060 msgid "``name`` is a raw string for the class name" msgstr "``name`` 为类名称的原始字符串。" #: ../../library/ast.rst:2061 msgid "``bases`` is a list of nodes for explicitly specified base classes." msgstr "``bases`` 为一个由显式指明的基类节点组成的列表。" #: ../../library/ast.rst:2062 msgid "" "``keywords`` is a list of :class:`.keyword` nodes, principally for " "'metaclass'. Other keywords will be passed to the metaclass, as per " ":pep:`3115`." msgstr "" "``keywords`` 是一个 :class:`.keyword` 节点的列表,主要用于‘元类’。 其他关键字将被传给相应的元类,参见 " ":pep:`3115`。" #: ../../library/ast.rst:2064 msgid "" "``body`` is a list of nodes representing the code within the class " "definition." msgstr "``body`` 是一个由代表类定义内部代码的节点组成的列表。" #: ../../library/ast.rst:2066 msgid "``decorator_list`` is a list of nodes, as in :class:`FunctionDef`." msgstr "``decorator_list`` 是一个节点的列表,与 :class:`FunctionDef` 中的一致。" #: ../../library/ast.rst:2069 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... @decorator1\n" "... @decorator2\n" "... class Foo(base1, base2, metaclass=meta):\n" "... pass\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " ClassDef(\n" " name='Foo',\n" " bases=[\n" " Name(id='base1', ctx=Load()),\n" " Name(id='base2', ctx=Load())],\n" " keywords=[\n" " keyword(\n" " arg='metaclass',\n" " value=Name(id='meta', ctx=Load()))],\n" " body=[\n" " Pass()],\n" " decorator_list=[\n" " Name(id='decorator1', ctx=Load()),\n" " Name(id='decorator2', ctx=Load())],\n" " type_params=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:2100 msgid "Async and await" msgstr "async 与 await" #: ../../library/ast.rst:2104 msgid "" "An ``async def`` function definition. Has the same fields as " ":class:`FunctionDef`." msgstr "一个 ``async def`` 函数定义。 具有与 :class:`FunctionDef` 相同的字段。" #: ../../library/ast.rst:2113 msgid "" "An ``await`` expression. ``value`` is what it waits for. Only valid in the " "body of an :class:`AsyncFunctionDef`." msgstr "" "一个 ``await`` 表达式。 ``value`` 是它所等待的值。 仅在 :class:`AsyncFunctionDef` 的函数体内可用。" #: ../../library/ast.rst:2116 msgid "" ">>> print(ast.dump(ast.parse(\"\"\"\\\n" "... async def f():\n" "... await other_func()\n" "... \"\"\"), indent=4))\n" "Module(\n" " body=[\n" " AsyncFunctionDef(\n" " name='f',\n" " args=arguments(\n" " posonlyargs=[],\n" " args=[],\n" " kwonlyargs=[],\n" " kw_defaults=[],\n" " defaults=[]),\n" " body=[\n" " Expr(\n" " value=Await(\n" " value=Call(\n" " func=Name(id='other_func', ctx=Load()),\n" " args=[],\n" " keywords=[])))],\n" " decorator_list=[],\n" " type_params=[])],\n" " type_ignores=[])" msgstr "" #: ../../library/ast.rst:2147 msgid "" "``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`." msgstr "" "``async for`` 循环和 ``async with`` 上下文管理器。 它们分别具有与 :class:`For` 和 " ":class:`With` 相同的字段。 仅在 :class:`AsyncFunctionDef` 的函数体内可用。" #: ../../library/ast.rst:2152 msgid "" "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 (e.g. :class:`ast.Add`)." msgstr "" "当一个字符串由 :func:`ast.parse` 来解析时,所返回的树中的运算符节点 (为 :class:`ast.operator`, " ":class:`ast.unaryop`, :class:`ast.cmpop`, :class:`ast.boolop` 和 " ":class:`ast.expr_context` 的子类) 将均为单例对象。 对其中某一个 (例如 :class:`ast.Add`) " "的修改将反映到同一个值所出现的其他位置上。" #: ../../library/ast.rst:2160 msgid ":mod:`ast` Helpers" msgstr ":mod:`ast` 中的辅助函数" #: ../../library/ast.rst:2162 msgid "" "Apart from the node classes, the :mod:`ast` module defines these utility " "functions and classes for traversing abstract syntax trees:" msgstr "除了节点类, :mod:`ast` 模块里为遍历抽象语法树定义了这些工具函数和类:" #: ../../library/ast.rst:2167 msgid "" "Parse the source into an AST node. Equivalent to ``compile(source, " "filename, mode, ast.PyCF_ONLY_AST)``." msgstr "" "把源码解析为AST节点。和 ``compile(source, filename, mode,ast.PyCF_ONLY_AST)`` 等价。" #: ../../library/ast.rst:2170 msgid "" "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)." msgstr "" "如果给出 ``type_comments=True``,解析器会被修改只检查并返回 :pep:`484` 和 :pep:`526` 所规定的类型注释。 " "这相当于将 :data:`ast.PyCF_TYPE_COMMENTS` 添加到传给 :func:`compile` 的旗标中。 " "这将报告针对未正确放置类型注释的语法错误。 没有这个旗标,类型注释将被忽略,而选定的 AST 节点上的 ``type_comment`` 字段将始终为 " "``None``。 此外,``# type: ignore`` 注释的位置将作为 :class:`Module` 的 ``type_ignores`` " "属性被返回(在其他情况下则总是为空列表)。attribute of (otherwise it is always an empty list)." #: ../../library/ast.rst:2180 msgid "" "In addition, if ``mode`` is ``'func_type'``, the input syntax is modified to" " correspond to :pep:`484` \"signature type comments\", e.g. ``(str, int) -> " "List[str]``." msgstr "" "并且,如果 ``mode`` 为 ``'func_type'``,则输入语法会进行与 :pep:`484` \"签名类型注释\" 对应的修改,例如 " "``(str, int) -> List[str]``。" #: ../../library/ast.rst:2184 msgid "" "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, 4)`` (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``." msgstr "" "将 ``feature_version`` 设置为元组 ``(major, minor)`` 将导致使用该 " "Python版语法\"尽力\"尝试解析。例如,设置 ``feature_version=(3, 9)`` 将尝试禁止解析 " ":keyword:`match` 语句 。目前, ``major`` 必须等于 ``3`` 。支持的最低版是 ``(3, 4)`` (在未来的 " "Python 版本中可能会增加);最高是 ``sys.version_info[0:2]`` 。\"尽力 \"尝试意味着不能保证解析 (或解析的成功) " "与在与 ``feature_version`` 对应的 Python版 上运行时相同。" #: ../../library/ast.rst:2194 msgid "" "If source contains a null character (``\\0``), :exc:`ValueError` is raised." msgstr "如果源包含一个空字符 (``\\0``),则会引发 :exc:`ValueError`。" #: ../../library/ast.rst:2197 msgid "" "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)." msgstr "" "请注意成功将源代码解析为 AST 对象并不能保证该源代码提供了可被执行的有效 Python 代码,因为编译步骤还可能引发其他的 " ":exc:`SyntaxError` 异常。 例如,对于源代码 ``return 42`` 可以生成一条有效的 return 语句 AST " "节点,但它不能被单独编译(它必须位于一个函数节点之内)。" #: ../../library/ast.rst:2204 msgid "" "In particular, :func:`ast.parse` won't do any scoping checks, which the " "compilation step does." msgstr "特别地,:func:`ast.parse` 不会执行任何作用域检查,这是由编译步骤来做的。" #: ../../library/ast.rst:2208 msgid "" "It is possible to crash the Python interpreter with a sufficiently " "large/complex string due to stack depth limitations in Python's AST " "compiler." msgstr "足够复杂或是巨大的字符串可能导致Python解释器的崩溃,因为Python的AST编译器是有栈深限制的。" #: ../../library/ast.rst:2212 msgid "Added ``type_comments``, ``mode='func_type'`` and ``feature_version``." msgstr "增加了 ``type_comments``, ``mode='func_type'`` 和 ``feature_version``。" #: ../../library/ast.rst:2218 msgid "" "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`." msgstr "" "反向解析一个 :class:`ast.AST` 对象并生成一个包含当再次使用 :func:`ast.parse` 解析时将产生同样的 " ":class:`ast.AST` 对象的代码的字符串。" #: ../../library/ast.rst:2223 msgid "" "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)." msgstr "" "所产生的代码字符串将不一定与生成 :class:`ast.AST` 对象的原始代码完全一致(不带任何编译器优化,例如常量元组/冻结集合等)。" #: ../../library/ast.rst:2228 msgid "" "Trying to unparse a highly complex expression would result with " ":exc:`RecursionError`." msgstr "尝试反向解析一个高度复杂的表达式可能会导致 :exc:`RecursionError`。" #: ../../library/ast.rst:2236 msgid "" "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``." msgstr "" "对表达式节点或仅包含 Python 字面值或容器表示形式的字符串进行求值。 所提供的字符串或节点可能只包含下列 Python " "字面值结构:字符串、字节串、数字、元组、字典、集合、布尔值、``None`` 和 ``Ellipsis``。" #: ../../library/ast.rst:2241 msgid "" "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." msgstr "" "这可被用于对包含 Python 值的字符串进行求值而不必解析这些值本身。 它不能对任意的复杂表达式进行求值,例如涉及运算符或索引操作的表达式。" #: ../../library/ast.rst:2246 msgid "" "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." msgstr "" "此函数过去曾被描述为“安全”但并未定义其含义。 这是存在误导性的。 此函数被专门设计为不执行 Python 代码,这与更通用的 :func:`eval`" " 不同。 它没有命名空间、没有名称查找或执行外部调用的能力。 但是它并不能完全避免攻击:一个相对较小的输入有可能导致内存耗尽或 C " "栈耗尽,使得进程崩溃。 还可能在某些输入上出现过度消耗 CPU 的拒绝服务问题。 因此不建议在未被信任的数据上调用它。" #: ../../library/ast.rst:2256 msgid "" "It is possible to crash the Python interpreter due to stack depth " "limitations in Python's AST compiler." msgstr "有可能由于 Python 的 AST 编译器中的栈深度限制而导致 Python 解释器的崩溃。" #: ../../library/ast.rst:2259 msgid "" "It can raise :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, " ":exc:`MemoryError` and :exc:`RecursionError` depending on the malformed " "input." msgstr "" "根据输入错误的具体形式它可能引发 :exc:`ValueError`, :exc:`TypeError`, :exc:`SyntaxError`, " ":exc:`MemoryError` 以及 :exc:`RecursionError`。" #: ../../library/ast.rst:2263 msgid "Now allows bytes and set literals." msgstr "目前支持字节和集合。" #: ../../library/ast.rst:2266 msgid "Now supports creating empty sets with ``'set()'``." msgstr "现在支持通过 ``'set()'`` 创建空集合。" #: ../../library/ast.rst:2269 msgid "For string inputs, leading spaces and tabs are now stripped." msgstr "对于字符串输入,打头的空格和制表符现在会被去除。" #: ../../library/ast.rst:2275 msgid "" "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`." msgstr "" "返回给定 *node* (必须为 :class:`FunctionDef`, :class:`AsyncFunctionDef`, " ":class:`ClassDef` 或 :class:`Module` 节点) 的文档字符串,或者如果没有文档字符串则返回 ``None``。 如果 " "*clean* 为真值,则通过 :func:`inspect.cleandoc` 清除文档字符串的缩进。" #: ../../library/ast.rst:2281 msgid ":class:`AsyncFunctionDef` is now supported." msgstr "目前支持 :class:`AsyncFunctionDef`" #: ../../library/ast.rst:2287 msgid "" "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``." msgstr "" "获取生成 *node* 的 *source* 的源代码段。 如果丢失了某些位置信息 (:attr:`~ast.AST.lineno`, " ":attr:`~ast.AST.end_lineno`, :attr:`~ast.AST.col_offset` 或 " ":attr:`~ast.AST.end_col_offset`),则返回 ``None``。" #: ../../library/ast.rst:2291 msgid "" "If *padded* is ``True``, the first line of a multi-line statement will be " "padded with spaces to match its original position." msgstr "如果 *padded* 为 ``True``,则多行语句的第一行将以与其初始位置相匹配的空格填充。" #: ../../library/ast.rst:2299 msgid "" "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*." msgstr "" "当你使用 :func:`compile` 来编译节点树时,编译器会接受每个支持 :attr:`~ast.AST.lineno` 和 " ":attr:`~ast.AST.col_offset` 属性的节点的相应信息。 " "对于已生成的节点来说这是相当繁琐的,因此这个辅助工具会递归地为尚未设置这些属性的节点添加它们,具体做法是将其设为父节点的对应值。 它将从 *node* " "开始递归地执行。" #: ../../library/ast.rst:2308 msgid "" "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." msgstr "从 *node* 开始按 *n* 递增节点树中每个节点的行号和结束行号。 这在“移动代码”到文件中的不同位置时很有用处。" #: ../../library/ast.rst:2315 msgid "" "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*." msgstr "" "在可能的情况下将源位置 (:attr:`~ast.AST.lineno`, :attr:`~ast.AST.col_offset`, " ":attr:`~ast.AST.end_lineno` 和 :attr:`~ast.AST.end_col_offset`) 从 *old_node* " "拷贝到 *new_node*,并返回 *new_node*。" #: ../../library/ast.rst:2322 msgid "" "Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields`` " "that is present on *node*." msgstr "" "针对于 *node* 上在 ``node._fields`` 中出现的每个字段产生一个 ``(fieldname, value)`` 元组。" #: ../../library/ast.rst:2328 msgid "" "Yield all direct child nodes of *node*, that is, all fields that are nodes " "and all items of fields that are lists of nodes." msgstr "产生 *node* 所有的直接子节点,也就是说,所有为节点的字段所有为节点列表的字段条目。" #: ../../library/ast.rst:2334 msgid "" "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." msgstr "" "递归地产生节点树中从 *node* 开始(包括 *node* 本身)的所有下级节点,没有确定的排序方式。 " "这在你仅想要原地修改节点而不关心具体上下文时很有用处。" #: ../../library/ast.rst:2341 msgid "" "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." msgstr "" "一个遍历抽象语法树并针对所找到的每个节点调用访问器函数的节点访问器基类。 该函数可能会返回一个由 :meth:`visit` 方法所提供的值。" #: ../../library/ast.rst:2345 msgid "" "This class is meant to be subclassed, with the subclass adding visitor " "methods." msgstr "这个类应当被子类化,并由子类来添加访问器方法。" #: ../../library/ast.rst:2350 msgid "" "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." msgstr "" "访问一个节点。 默认实现会调用名为 :samp:`self.visit_{classname}` 的方法其中 *classname* " "为节点类的名称,或者如果该方法不存在则为 :meth:`generic_visit`。" #: ../../library/ast.rst:2356 msgid "This visitor calls :meth:`visit` on all children of the node." msgstr "该访问器会在节点的所有子节点上调用 :meth:`visit`。" #: ../../library/ast.rst:2358 msgid "" "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." msgstr "请注意所有包含自定义访问器方法的节点的子节点将不会被访问除非访问器调用了 :meth:`generic_visit` 或是自行访问它们。" #: ../../library/ast.rst:2364 msgid "Handles all constant nodes." msgstr "处理所有常量节点。" #: ../../library/ast.rst:2366 msgid "" "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." msgstr "" "如果你想在遍历期间应用对节点的修改则请不要使用 :class:`NodeVisitor`。 对此目的可使用一个允许修改的特殊访问器 " "(:class:`NodeTransformer`)。" #: ../../library/ast.rst:2372 msgid "" "Methods :meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, " ":meth:`!visit_NameConstant` and :meth:`!visit_Ellipsis` are deprecated now " "and will not be called in future Python versions. Add the " ":meth:`visit_Constant` method to handle all constant nodes." msgstr "" ":meth:`!visit_Num`, :meth:`!visit_Str`, :meth:`!visit_Bytes`, " ":meth:`!visit_NameConstant` 和 :meth:`!visit_Ellipsis` 等方法现在已被弃用并且在未来的 Python" " 版本中将不再被调用。 请添加 :meth:`visit_Constant` 方法来处理所有常量节点。" #: ../../library/ast.rst:2380 msgid "" "A :class:`NodeVisitor` subclass that walks the abstract syntax tree and " "allows modification of nodes." msgstr "子类 :class:`NodeVisitor` 用于遍历抽象语法树,并允许修改节点。" #: ../../library/ast.rst:2383 msgid "" "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." msgstr "" ":class:`NodeTransformer` 将遍历抽象语法树并使用visitor方法的返回值去替换或移除旧节点。如果visitor方法的返回值为 " "``None`` , 则该节点将从其位置移除,否则将替换为返回值。当返回值是原始节点时,无需替换。" #: ../../library/ast.rst:2389 msgid "" "Here is an example transformer that rewrites all occurrences of name lookups" " (``foo``) to ``data['foo']``::" msgstr "如下是一个转换器示例,它将所有出现的名称 (``foo``) 重写为 ``data['foo']``::" #: ../../library/ast.rst:2392 msgid "" "class RewriteName(NodeTransformer):\n" "\n" " def visit_Name(self, node):\n" " return Subscript(\n" " value=Name(id='data', ctx=Load()),\n" " slice=Constant(value=node.id),\n" " ctx=node.ctx\n" " )" msgstr "" "class RewriteName(NodeTransformer):\n" "\n" " def visit_Name(self, node):\n" " return Subscript(\n" " value=Name(id='data', ctx=Load()),\n" " slice=Constant(value=node.id),\n" " ctx=node.ctx\n" " )" #: ../../library/ast.rst:2401 msgid "" "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." msgstr "" "请记住如果你正在操作的节点具有子节点,你必须先自行转换这些子节点或是为该节点调用 " ":meth:`~ast.NodeVisitor.generic_visit` 方法。" #: ../../library/ast.rst:2405 msgid "" "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." msgstr "对于属于语句集合(适用于所有语句节点)的节点,访问者还可以返回节点列表而不仅仅是单个节点。" #: ../../library/ast.rst:2409 msgid "" "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::" msgstr "" "如果 :class:`NodeTransformer` 引入了新的(不属于原节点树的一部分的)节点而没有给出它们的位置信息(如 " ":attr:`~ast.AST.lineno` 等),则应当调用 :func:`fix_missing_locations` " "并传入新的子节点树来重新计算位置信息::" #: ../../library/ast.rst:2414 msgid "" "tree = ast.parse('foo', mode='eval')\n" "new_tree = fix_missing_locations(RewriteName().visit(tree))" msgstr "" "tree = ast.parse('foo', mode='eval')\n" "new_tree = fix_missing_locations(RewriteName().visit(tree))" #: ../../library/ast.rst:2417 msgid "Usually you use the transformer like this::" msgstr "通常你可以像这样使用转换器::" #: ../../library/ast.rst:2419 msgid "node = YourTransformer().visit(node)" msgstr "node = YourTransformer().visit(node)" #: ../../library/ast.rst:2424 msgid "" "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." msgstr "" "返回 *node* 中树结构的格式化转储。 这主要适用于调试目的。 如果 *annotate_fields* " "为真值(默认),返回的字符串将显示字段的名称和值。 如果 *annotate_fields* 为假值,结果字符串将通过省略无歧义的字段名称变得更为紧凑。" " 默认情况下不会转储行号和列偏移等属性。 如果需要,可将 *include_attributes* 设为真值。" #: ../../library/ast.rst:2432 msgid "" "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." msgstr "" "如果 *indent* 是一个非负整数或者字符串,那么节点树将被美化输出为指定的缩进级别。 如果缩进级别为 0、负数或者 ``\"\"`` " "则将只插入换行符。 ``None`` (默认) 将选择最紧凑的表示形式。 使用一个正整数将让每个级别缩进相应数量的空格。 如果 *indent* " "是一个字符串 (如 ``\"\\t\"``),该字符串会被用于缩进每个级别。" #: ../../library/ast.rst:2439 msgid "Added the *indent* option." msgstr "添加了 *indent* 选项。" #: ../../library/ast.rst:2446 msgid "Compiler Flags" msgstr "编译器旗标" #: ../../library/ast.rst:2448 msgid "" "The following flags may be passed to :func:`compile` in order to change " "effects on the compilation of a program:" msgstr "下列旗标可被传给 :func:`compile` 用来改变程序编译的效果:" #: ../../library/ast.rst:2453 msgid "" "Enables support for top-level ``await``, ``async for``, ``async with`` and " "async comprehensions." msgstr "启用对最高层级 ``await``, ``async for``, ``async with`` 以及异步推导式的支持。" #: ../../library/ast.rst:2460 msgid "" "Generates and returns an abstract syntax tree instead of returning a " "compiled code object." msgstr "生成并返回一个抽象语法树而不是返回一个已编译的代码对象。" #: ../../library/ast.rst:2465 msgid "" "Enables support for :pep:`484` and :pep:`526` style type comments (``# type:" " ``, ``# type: ignore ``)." msgstr "" "启用对 :pep:`484` 和 :pep:`526` 风格的类型注释的支持 (``# type: ``, ``# type: ignore" " ``)。" #: ../../library/ast.rst:2474 msgid "Command-Line Usage" msgstr "命令行用法" #: ../../library/ast.rst:2478 msgid "" "The :mod:`ast` module can be executed as a script from the command line. It " "is as simple as:" msgstr ":mod:`ast` 模块可以在命令行下作为脚本来执行。 具体做法非常简单:" #: ../../library/ast.rst:2481 msgid "python -m ast [-m ] [-a] [infile]" msgstr "python -m ast [-m ] [-a] [infile]" #: ../../library/ast.rst:2485 msgid "The following options are accepted:" msgstr "可以接受以下选项:" #: ../../library/ast.rst:2491 msgid "Show the help message and exit." msgstr "显示帮助信息并退出。" #: ../../library/ast.rst:2496 msgid "" "Specify what kind of code must be compiled, like the *mode* argument in " ":func:`parse`." msgstr "指明哪种代码必须被编译,相当于 :func:`parse` 中的 *mode* 参数。" #: ../../library/ast.rst:2501 msgid "Don't parse type comments." msgstr "不要解析类型注释。" #: ../../library/ast.rst:2505 msgid "Include attributes such as line numbers and column offsets." msgstr "包括属性如行号和列偏移。" #: ../../library/ast.rst:2510 msgid "Indentation of nodes in AST (number of spaces)." msgstr "AST 中节点的缩进(空格数)。" #: ../../library/ast.rst:2512 msgid "" "If :file:`infile` is specified its contents are parsed to AST and dumped to " "stdout. Otherwise, the content is read from stdin." msgstr "如果指定了 :file:`infile` 则其内容将被解析为 AST 并转储至 stdout。 在其他情况下,将从 stdin 读取内容。" #: ../../library/ast.rst:2518 msgid "" "`Green Tree Snakes `_, an external " "documentation resource, has good details on working with Python ASTs." msgstr "" "`Green Tree Snakes `_,一个外部文档资源,包含处理" " Python AST 的完整细节。" #: ../../library/ast.rst:2521 msgid "" "`ASTTokens `_ " "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." msgstr "" "`ASTTokens `_ 会为" " Python AST 标注生成它们的源代码中的形符和文本的位置。 这对执行源代码转换的工具很有帮助。" #: ../../library/ast.rst:2526 msgid "" "`leoAst.py `_ unifies the token-based and parse-tree-based views of python programs " "by inserting two-way links between tokens and ast nodes." msgstr "" "`leoAst.py `_ 通过在形符和 ast 节点之间插入双向链接统一了 python 程序基于形符的和基于解析树的视图。" #: ../../library/ast.rst:2531 msgid "" "`LibCST `_ 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." msgstr "" "`LibCST `_ 将代码解析为一个实体语法树(Concrete Syntax " "Tree),它看起来像是 ast 树而又保留了所有格式化细节。 它对构建自动化重构(codemod)应用和代码质量检查工具很有用处。" #: ../../library/ast.rst:2536 msgid "" "`Parso `_ 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." msgstr "" "`Parso `_ 是一个支持错误恢复和不同 Python 版本的(在多个 Python " "版本中)往返解析的 Python 解析器。 Parso 还能列出你的 Python 文件中的许多语法错误。" #: ../../library/ast.rst:59 msgid "? (question mark)" msgstr "? (问号)" #: ../../library/ast.rst:59 ../../library/ast.rst:60 msgid "in AST grammar" msgstr "在 AST 语法中" #: ../../library/ast.rst:60 msgid "* (asterisk)" msgstr "* (星号)"