Teks sumber — English
Terjemahan — Bahasa Indonesia
When a description of an arithmetic operator below uses the phrase "the numeric arguments are converted to a common real type", this means that the operator implementation for built-in numeric types works as described in the :ref:`Numeric Types <stdtypes-mixed-arithmetic>` section of the standard library documentation.
The :attr:`~definition.__name__` attribute of nested functions, classes, and type aliases is however not mangled.
Evaluation of a literal yields an object of the given type (:class:`int`, :class:`float`, :class:`complex`, :class:`str`, :class:`bytes`, or :class:`~string.templatelib.Template`) with the given value. The value may be approximated in the case of floating-point and imaginary literals.
All literals correspond to immutable data types, and hence the object's identity is less important than its value. Multiple evaluations of literals with the same value (either the same occurrence in the program text or a different occurrence) may obtain the same object or a different object with the same value.
At runtime, when a display is evaluated, the listed items are evaluated from left to right and placed into a new container of the appropriate type.
To ensure the comprehension always results in a container of the appropriate type, ``yield`` and ``yield from`` expressions are prohibited in the implicitly nested scope.
>>> (x ** 2 for x in None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is not iterable
When ``yield from <expr>`` is used, the supplied expression must be an iterable. The values produced by iterating that iterable are passed directly to the caller of the current generator's methods. Any values passed in with :meth:`~generator.send` and any exceptions passed in with :meth:`~generator.throw` are passed to the underlying iterator if it has the appropriate methods. If this is not the case, then :meth:`~generator.send` will raise :exc:`AttributeError` or :exc:`TypeError`, while :meth:`~generator.throw` will just raise the passed in exception immediately.
>>> def echo(value=None):
... print("Execution starts when 'next()' is called for the first time.")
... try:
... while True:
... try:
... value = (yield value)
... except Exception as e:
... value = e
... finally:
... print("Don't forget to clean up when 'close()' is called.")
...
>>> generator = echo(1)
>>> print(next(generator))
Execution starts when 'next()' is called for the first time.
1
>>> print(next(generator))
None
>>> print(generator.send(2))
2
>>> generator.throw(TypeError, "spam")
TypeError('spam',)
>>> generator.close()
Don't forget to clean up when 'close()' is called.
The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier. The type and value produced is determined by the object. Multiple evaluations of the same attribute reference may yield different objects.
The :dfn:`subscription` syntax is usually used for selecting an element from a :ref:`container <sequence-types>` -- for example, to get a value from a :class:`dict`::
Depending on the type of the object being subscribed, the subscript is sometimes called a :term:`key` (for mappings), :term:`index` (for sequences), or *type argument* (for :term:`generic types <generic type>`). Syntactically, these are all equivalent::
>>> colors = ['red', 'blue', 'green', 'black']
>>> colors[3] # Subscripting a list using the index 3
'black'
>>> list[str] # Parameterizing the list type using the type argument str
list[str]
See :meth:`~object.__getitem__` documentation for how built-in types handle subscription.
If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a :exc:`TypeError` exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is ``None``, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a :exc:`TypeError` exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.
If there are more positional arguments than there are formal parameter slots, a :exc:`TypeError` exception is raised, unless a formal parameter using the syntax ``*identifier`` is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a :exc:`TypeError` exception is raised, unless a formal parameter using the syntax ``**identifier`` is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.
>>> def f(a, b):
... print(a, b)
...
>>> f(b=1, *(2,))
2 1
>>> f(a=1, *(2,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got multiple values for keyword argument 'a'
>>> f(1, *(2,))
1 2
If the syntax ``**expression`` appears in the function call, ``expression`` must evaluate to a :term:`mapping`, the contents of which are treated as additional keyword arguments. If a parameter matching a key has already been given a value (by an explicit keyword argument, or from another unpacking), a :exc:`TypeError` exception is raised.
When ``**expression`` is used, each key in this mapping must be a string. Each value from the mapping is assigned to the first formal parameter eligible for keyword assignment whose name is equal to the key. A key need not be a Python identifier (e.g. ``"max-temp °F"`` is acceptable, although it will not match any formal parameter that could be declared). If there is no match to a formal parameter the key-value pair is collected by the ``**`` parameter, if there is one, or if there is not, a :exc:`TypeError` exception is raised.
A call always returns some value, possibly ``None``, unless it raises an exception. How this value is computed depends on the type of the callable object.
The power operator has the same semantics as the built-in :func:`pow` function, when called with two arguments: it yields its left argument raised to the power of its right argument. Numeric arguments are first :ref:`converted to a common type <stdtypes-mixed-arithmetic>`, and the result is of that type.
For int operands, the result has the same type as the operands unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``.
In all three cases, if the argument does not have the proper type, a :exc:`TypeError` exception is raised.
The binary arithmetic operations have the conventional priority levels. Note that some of these operations also apply to certain non-numeric types. Apart from the power operator, there are only two levels, one for multiplicative operators and one for additive operators:
The ``*`` (multiplication) operator yields the product of its arguments. The arguments must either both be numbers, or one argument must be an integer and the other must be a sequence. In the former case, the numbers are :ref:`converted to a common real type <stdtypes-mixed-arithmetic>` and then multiplied together. In the latter case, sequence repetition is performed; a negative repetition factor yields an empty sequence.
The ``@`` (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.
The ``/`` (division) and ``//`` (floor division) operators yield the quotient of their arguments. The numeric arguments are first :ref:`converted to a common type <stdtypes-mixed-arithmetic>`. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result. Division by zero raises the :exc:`ZeroDivisionError` exception.
The ``%`` (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first :ref:`converted to a common type <stdtypes-mixed-arithmetic>`. A zero right argument raises the :exc:`ZeroDivisionError` exception. The arguments may be floating-point numbers, e.g., ``3.14%0.7`` equals ``0.34`` (since ``3.14`` equals ``4*0.7 + 0.34``.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [#]_.
The ``+`` (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both be sequences of the same type. In the former case, the numbers are :ref:`converted to a common real type <stdtypes-mixed-arithmetic>` and then added together. In the latter case, the sequences are concatenated.
The ``-`` (subtraction) operator yields the difference of its arguments. The numeric arguments are first :ref:`converted to a common real type <stdtypes-mixed-arithmetic>`.
The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the values of two objects. The objects do not need to have the same type.
Chapter :ref:`objects` states that objects have a value (in addition to type and identity). The value of an object is a rather abstract notion in Python: For example, there is no canonical access method for an object's value. Also, there is no requirement that the value of an object should be constructed in a particular way, e.g. comprised of all its data attributes. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.
Because all types are (direct or indirect) subtypes of :class:`object`, they inherit the default comparison behavior from :class:`object`. Types can customize their comparison behavior by implementing :dfn:`rich comparison methods` like :meth:`~object.__lt__`, described in :ref:`customization`.
A default order comparison (``<``, ``>``, ``<=``, and ``>=``) is not provided; an attempt raises :exc:`TypeError`. A motivation for this default behavior is the lack of a similar invariant as for equality.
The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.
The following list describes the comparison behavior of the most important built-in types.
Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be compared within and across their types, with the restriction that complex numbers do not support order comparison. Within the limits of the types involved, they compare mathematically (algorithmically) correct without loss of precision.
Binary sequences (instances of :class:`bytes` or :class:`bytearray`) can be compared within and across their types. They compare lexicographically using the numeric values of their elements.
Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises :exc:`TypeError`.
For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example, ``[1,2] == (1,2)`` is false because the type is not the same).
Order comparisons (``<``, ``>``, ``<=``, and ``>=``) raise :exc:`TypeError`.
Sets (instances of :class:`set` or :class:`frozenset`) can be compared within and across their types.
Most other built-in types have no comparison methods implemented, so they inherit the default comparison behavior.
The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. ``x not in s`` returns the negation of ``x in s``. All built-in sequences and set types support this as well as dictionary, for which :keyword:`!in` tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent to ``any(x is e or x == e for e in y)``.
For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a substring of *y*. An equivalent test is ``y.find(x) != -1``. Empty strings are always considered to be a substring of any other string, so ``"" in "abc"`` will return ``True``.
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: ``False``, ``None``, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a :meth:`~object.__bool__` method.
Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type they return to ``False`` and ``True``, but rather return the last evaluated argument. This is sometimes useful, e.g., if ``s`` is a string that should be replaced by a default value if it is empty, the expression ``s or 'foo'`` yields the desired value. Because :keyword:`not` has to create a new value, it returns a boolean value regardless of the type of its argument (for example, ``not 'foo'`` produces ``False`` rather than ``''``.)
type
tipe
TypeError