Pelokalan
Python ID
id en
Masuk
Proyek
reference__compound_stmts.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
The :keyword:`for` statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:
The :token:`~python-grammar:starred_expression_list` expression is evaluated once; it should yield an :term:`iterable` object. An :term:`iterator` is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see :ref:`assignment`), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is :term:`exhausted`, the suite in the :keyword:`!else` clause, if present, is executed, and the loop terminates.
The for-loop makes assignments to the variables in the target list. This overwrites all previous assignments to those variables including those made in the suite of the for-loop::
Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type :func:`range` represents immutable arithmetic sequences of integers. For instance, iterating ``range(3)`` successively yields 0, 1, and then 2.
Starred elements are now allowed in the expression list.
The :keyword:`with` statement guarantees that if the :meth:`~object.__enter__` method returns without an error, then :meth:`~object.__exit__` will always be called. Thus, if an error occurs during the assignment to the target list, it will be treated the same as an error occurring within the suite would be. See step 7 below.
A sequence pattern contains several subpatterns to be matched against sequence elements. The syntax is similar to the unpacking of a list or tuple.
If the previous step succeeds, the star subpattern matches a list formed of the remaining subject items, excluding the remaining items corresponding to non-star subpatterns following the star subpattern.
:class:`list`
A list of :ref:`type parameters <type-params>` may be given in square brackets between the function's name and the opening parenthesis for its parameter list. This indicates to static type checkers that the function is generic. At runtime, the type parameters can be retrieved from the function's :attr:`~function.__type_params__` attribute. See :ref:`generic-functions` for more.
Type parameter lists are new in Python 3.12.
**Default parameter values are evaluated from left to right when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call. This is especially important to understand when a default parameter value is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default parameter value is in effect modified. This is generally not what was intended. A way around this is to use ``None`` as the default, and explicitly test for it in the body of the function, for example::
Function call semantics are described in more detail in section :ref:`calls`. A function call always assigns values to all parameters mentioned in the parameter list, either from positional arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form "``**identifier``" is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after "``*``" or "``*identifier``" are keyword-only parameters and may only be passed by keyword arguments. Parameters before "``/``" are positional-only parameters and may only be passed by positional arguments.
Parameters may have an :term:`annotation <function annotation>` of the form "``: expression``" following the parameter name. Any parameter may have an annotation, even those of the form ``*identifier`` or ``**identifier``. (As a special case, parameters of the form ``*identifier`` may have an annotation "``: *expression``".) Functions may have "return" annotation of the form "``-> expression``" after the parameter list. These annotations can be any valid Python expression. The presence of annotations does not change the semantics of a function. See :ref:`annotations` for more information on annotations.
A class definition is an executable statement. The inheritance list usually gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class :class:`object`; hence, ::
The class's suite is then executed in a new execution frame (see :ref:`naming`), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly function definitions.) When the class's suite finishes execution, its execution frame is discarded but its local namespace is saved. [#]_ A class object is then created using the inheritance list for the base classes and the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace.
A list of :ref:`type parameters <type-params>` may be given in square brackets immediately after the class's name. This indicates to static type checkers that the class is generic. At runtime, the type parameters can be retrieved from the class's :attr:`~type.__type_params__` attribute. See :ref:`generic-classes` for more.
Python classes may have multiple base classes, a technique known as *multiple inheritance*. The base classes are specified in the class definition by listing them in parentheses after the class name, separated by commas. For example, the following class definition:
In the resolved MRO of a class, the class's bases appear in the order they were specified in the class's bases list. Additionally, the MRO always lists a child class before any of its bases. A class definition will fail if it is impossible to resolve a consistent MRO that satisfies these rules from the list of bases provided:
In the MRO of ``Grandchild``, ``Base`` must appear before ``Child`` because it is first in the base class list, but it must also appear after ``Child`` because it is a parent of ``Child``. This is a contradiction, so the class cannot be defined.
Every class has a solid base. :class:`object`, the base class, has itself as its solid base. If there is a single base, the child class's solid base is that class if it is a solid base, or else the base class's solid base. If there are multiple bases, we first find the solid base for each base class to produce a list of candidate solid bases. If there is a unique solid base that is a subclass of all others, then that class is the solid base. Otherwise, class creation fails.
Type parameter lists
:ref:`Functions <def>` (including :ref:`coroutines <async def>`), :ref:`classes <class>` and :ref:`type aliases <type>` may contain a type parameter list::
def max[T](args: list[T]) -> T: ... async def amax[T](args: list[T]) -> T: ... class Bag[T]: def __iter__(self) -> Iterator[T]: ... def add(self, arg: T) -> None: ... type ListOrSet[T] = list[T] | set[T]
Generic functions, classes, and type aliases have a :attr:`~definition.__type_params__` attribute listing their type parameters.
:data:`typing.TypeVar` declarations can define *bounds* and *constraints* with a colon (``:``) followed by an expression. A single expression after the colon indicates a bound (e.g. ``T: int``). Semantically, this means that the :data:`!typing.TypeVar` can only represent types that are a subtype of this bound. A parenthesized tuple of expressions after the colon indicates a set of constraints (e.g. ``T: (str, bytes)``). Each member of the tuple should be a type (again, this is not enforced at runtime). Constrained type variables can only take on one of the types in the list of constraints.
For :data:`!typing.TypeVar`\ s declared using the type parameter list syntax, the bound and constraints are not evaluated when the generic object is created, but only when the value is explicitly accessed through the attributes ``__bound__`` and ``__constraints__``. To accomplish this, the bounds or constraints are evaluated in a separate :ref:`annotation scope <annotation-scopes>`.
type ListOrSet[T] = list[T] | set[T]
annotation-def TYPE_PARAMS_OF_ListOrSet(): T = typing.TypeVar("T") annotation-def VALUE_OF_ListOrSet(): return list[T] | set[T] # In reality, the value is lazily evaluated return typing.TypeAliasType("ListOrSet", VALUE_OF_ListOrSet(), type_params=(T,)) ListOrSet = TYPE_PARAMS_OF_ListOrSet()
Here, ``annotation-def`` (not a real keyword) indicates an :ref:`annotation scope <annotation-scopes>`. The capitalized names like ``TYPE_PARAMS_OF_ListOrSet`` are not actually bound at runtime.
list
list
parameter list
expression list