Pelokalan
Python ID
id en
Masuk
Proyek
builtins__stdtypes.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
Some operations are supported by several object types; in particular, practically all objects can be compared for equality, tested for truth value, and converted to a string (with the :func:`repr` function or the slightly different :func:`str` function). The latter function is implicitly used when an object is written by the :func:`print` function.
Beberapa operasi didukung oleh beberapa jenis objek; khususnya, secara praktis semua objek dapat dibandingkan untuk kesetaraan, diuji untuk nilai kebenaran, dan dikonversi ke string (dengan fungsi :func:`repr` atau yang sedikit berbeda fungsi :func:`str`). Fungsi terakhir secara implisit digunakan ketika suatu objek ditulis oleh fungsi :func:`print`.
Any object can be tested for truth value, for use in an :keyword:`if` or :keyword:`while` condition or as operand of the Boolean operations below.
Objek apa pun dapat diuji untuk nilai kebenaran, untuk digunakan dalam :keyword:`if` atau kondisi :keyword:`while` atau sebagai operan dari operasi *Boolean* di bawah ini.
By default, an object is considered true unless its class defines either a :meth:`~object.__bool__` method that returns ``False`` or a :meth:`~object.__len__` method that returns zero, when called with the object. [1]_ If one of the methods raises an exception when called, the exception is propagated and the object does not have a truth value (for example, :data:`NotImplemented`). Here are most of the built-in objects considered false:
object identity
identitas objek
negated object identity
identitas objek dinegasikan
Unless stated otherwise, objects of different types never compare equal. The ``==`` operator is always defined but for some object types (for example, class objects) is equivalent to :keyword:`is`. The ``<``, ``<=``, ``>`` and ``>=`` operators are only defined where they make sense; for example, they raise a :exc:`TypeError` exception when one of the arguments is a complex number.
Non-identical instances of a class normally compare as non-equal unless the class defines the :meth:`~object.__eq__` method.
Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods :meth:`~object.__lt__`, :meth:`~object.__le__`, :meth:`~object.__gt__`, and :meth:`~object.__ge__` (in general, :meth:`~object.__lt__` and :meth:`~object.__eq__` are sufficient, if you want the conventional meanings of the comparison operators).
The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be customized; also they can be applied to any two objects and never raise an exception.
Two more operations with the same syntactic priority, :keyword:`in` and :keyword:`not in`, are supported by types that are :term:`iterable` or implement the :meth:`~object.__contains__` method.
The default values can be used to conveniently turn an integer into a single byte object::
The argument *bytes* must either be a :term:`bytes-like object` or an iterable producing bytes.
For a general Python object ``x``, ``float.from_number(x)`` delegates to ``x.__float__()``. If :meth:`~object.__float__` is not defined then it falls back to :meth:`~object.__index__`.
For a general Python object ``x``, ``complex.from_number(x)`` delegates to ``x.__complex__()``. If :meth:`~object.__complex__` is not defined then it falls back to :meth:`~object.__float__`. If :meth:`!__float__` is not defined then it falls back to :meth:`~object.__index__`.
For numbers ``x`` and ``y``, possibly of different types, it's a requirement that ``hash(x) == hash(y)`` whenever ``x == y`` (see the :meth:`~object.__hash__` method documentation for more details). For ease of implementation and efficiency across a variety of numeric types (including :class:`int`, :class:`float`, :class:`decimal.Decimal` and :class:`fractions.Fraction`) Python's hash for numeric types is based on a single mathematical function that's defined for any rational number, and hence applies to all instances of :class:`int` and :class:`fractions.Fraction`, and all finite instances of :class:`float` and :class:`decimal.Decimal`. Essentially, this function is given by reduction modulo ``P`` for a fixed prime ``P``. The value of ``P`` is made available to Python as the :attr:`~sys.hash_info.modulus` attribute of :data:`sys.hash_info`.
import sys, math def hash_fraction(m, n): """Compute the hash of a rational number m / n. Assumes m and n are integers, with n positive. Equivalent to hash(fractions.Fraction(m, n)). """ P = sys.hash_info.modulus # Remove common factors of P. (Unnecessary if m and n already coprime.) while m % P == n % P == 0: m, n = m // P, n // P if n % P == 0: hash_value = sys.hash_info.inf else: # Fermat's Little Theorem: pow(n, P-1, P) is 1, so # pow(n, P-2, P) gives the inverse of n modulo P. hash_value = (abs(m) % P) * pow(n, P - 2, P) % P if m < 0: hash_value = -hash_value if hash_value == -1: hash_value = -2 return hash_value def hash_float(x): """Compute the hash of a float x.""" if math.isnan(x): return object.__hash__(x) elif math.isinf(x): return sys.hash_info.inf if x > 0 else -sys.hash_info.inf else: return hash_fraction(*x.as_integer_ratio()) def hash_complex(z): """Compute the hash of a complex number z.""" hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag) # do a signed reduction modulo 2**sys.hash_info.width M = 2**(sys.hash_info.width - 1) hash_value = (hash_value & (M - 1)) - (hash_value & M) if hash_value == -1: hash_value = -2 return hash_value
One method needs to be defined for container objects to provide :term:`iterable` support:
Return an :term:`iterator` object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C API.
The iterator objects themselves are required to support the following two methods, which together form the :dfn:`iterator protocol`:
Return the :term:`iterator` object itself. This is required to allow both containers and iterators to be used with the :keyword:`for` and :keyword:`in` statements. This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C API.
Return the next item from the :term:`iterator`. If there are no further items, raise the :exc:`StopIteration` exception. This method corresponds to the :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the Python/C API.
Python defines several iterator objects to support iteration over general and specific sequence types, dictionaries, and other more specialized forms. The specific types are not important beyond their implementation of the iterator protocol.
>>> count_to_three() <generator object count_to_three at 0x7f33a2305000>
One common use for generator functions is implementing the :meth:`~object.__iter__` method of custom iterable objects. For example::
There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of :ref:`binary data <binaryseq>` and :ref:`text strings <textseq>` are described in dedicated sections.
This table lists the sequence operations sorted in ascending priority. In the table, *s* and *t* are sequences of the same type, *n*, *i*, *j* and *k* are integers and *x* is an arbitrary object that meets any type and value restrictions imposed by *s*.
Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost, you must switch to one of the alternatives below:
if concatenating :class:`str` objects, you can build a list and use :meth:`str.join` at the end or else write to an :class:`io.StringIO` instance and retrieve its value when complete
if concatenating :class:`bytes` objects, you can similarly use :meth:`bytes.join` or :class:`io.BytesIO`, or you can do in-place concatenation with a :class:`bytearray` object. :class:`bytearray` objects are mutable and have an efficient overallocation mechanism
if concatenating :class:`tuple` objects, extend a :class:`list` instead
In the table *s* is an instance of a mutable sequence type, *t* is any iterable object and *x* is an arbitrary object that meets any type and value restrictions imposed by *s* (for example, :class:`bytearray` only accepts integers that meet the value restriction ``0 <= x <= 255``).
The value *n* is an integer, or an object implementing :meth:`~object.__index__`. Zero and negative values of *n* clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for ``s * n`` under :ref:`typesseq-common`.
The constructor builds a list whose items are the same and in the same order as *iterable*'s items. *iterable* may be either a sequence, a container that supports iteration, or an iterator object. If *iterable* is already a list, a copy is made and returned, similar to ``iterable[:]``. For example, ``list('abc')`` returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``. If no argument is given, the constructor creates a new empty list, ``[]``.
For detailed information on thread-safety guarantees for :class:`list` objects, see :ref:`thread-safety-list`.
The constructor builds a tuple whose items are the same and in the same order as *iterable*'s items. *iterable* may be either a sequence, a container that supports iteration, or an iterator object. If *iterable* is already a tuple, it is returned unchanged. For example, ``tuple('abc')`` returns ``('a', 'b', 'c')`` and ``tuple( [1, 2, 3] )`` returns ``(1, 2, 3)``. If no argument is given, the constructor creates a new empty tuple, ``()``.
For heterogeneous collections of data where access by name is clearer than access by index, :func:`collections.namedtuple` may be a more appropriate choice than a simple tuple object.
The arguments to the range constructor must be integers (either built-in :class:`int` or any object that implements the :meth:`~object.__index__` special method). If the *step* argument is omitted, it defaults to ``1``. If the *start* argument is omitted, it defaults to ``0``. If *step* is zero, :exc:`ValueError` is raised.
A range object will be empty if ``r[0]`` does not meet the value constraint. Ranges do support negative indices, but these are interpreted as indexing from the end of the sequence determined by the positive indices.
Ranges implement all of the :ref:`common <typesseq-common>` sequence operations except concatenation and repetition (due to the fact that range objects can only represent sequences that follow a strict pattern and repetition and concatenation will usually violate that pattern).
The advantage of the :class:`range` type over a regular :class:`list` or :class:`tuple` is that a :class:`range` object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the ``start``, ``stop`` and ``step`` values, calculating individual items and subranges as needed).
Range objects implement the :class:`collections.abc.Sequence` ABC, and provide features such as containment tests, element index lookup, slicing and support for negative indices (see :ref:`typesseq`):
Testing range objects for equality with ``==`` and ``!=`` compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` attributes, for example ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.)
Implement the Sequence ABC. Support slicing and negative indices. Test :class:`int` objects for membership in constant time instead of iterating through all items.
Define '==' and '!=' to compare range objects based on the sequence of values they define (instead of comparing based on object identity).
Textual data in Python is handled with :class:`str` objects, or :dfn:`strings`. Strings are immutable :ref:`sequences <typesseq>` of Unicode code points. String literals are written in a variety of ways:
Strings may also be created from other objects using the :class:`str` constructor.
Return a :ref:`string <textseq>` version of *object*. If *object* is not provided, returns the empty string. Otherwise, the behavior of ``str()`` depends on whether *encoding* or *errors* is given, as follows.
If neither *encoding* nor *errors* is given, ``str(object)`` returns :meth:`type(object).__str__(object) <object.__str__>`, which is the "informal" or nicely printable string representation of *object*. For string objects, this is the string itself. If *object* does not have a :meth:`~object.__str__` method, then :func:`str` falls back to returning :func:`repr(object) <repr>`.
If at least one of *encoding* or *errors* is given, *object* should be a :term:`bytes-like object` (e.g. :class:`bytes` or :class:`bytearray`). In this case, if *object* is a :class:`bytes` (or :class:`bytearray`) object, then ``str(bytes, encoding, errors)`` is equivalent to :meth:`bytes.decode(encoding, errors) <bytes.decode>`. Otherwise, the bytes object underlying the buffer object is obtained before calling :meth:`bytes.decode`. See :ref:`binaryseq` and :ref:`bufferobjects` for information on buffer objects.
Passing a :class:`bytes` object to :func:`str` without the *encoding* or *errors* arguments falls under the first case of returning the informal string representation (see also the :option:`-b` command-line option to Python). For example::
Return a string which is the concatenation of the strings in *iterable*. A :exc:`TypeError` will be raised if there are any non-string values in *iterable*, including :class:`bytes` objects. The separator between elements is the string providing this method. For example:
Return a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via :meth:`~object.__getitem__`, typically a :term:`mapping` or :term:`sequence`. When indexed by a Unicode ordinal (an integer), the table object can do any of the following: return a Unicode ordinal or a string, to map the character to one or more other characters; return ``None``, to delete the character from the return string; or raise a :exc:`LookupError` exception, to map the character to itself.
Rather than evaluating to a ``str`` object, template string literals evaluate to a :class:`string.templatelib.Template` object.
The :func:`format` protocol is not used. Instead, the format specifier and conversions (if any) are passed to a new :class:`~string.templatelib.Interpolation` object that is created for each evaluated expression. It is up to code that processes the resulting :class:`~string.templatelib.Template` object to decide how to handle format specifiers and conversions.
Format specifiers containing nested replacement fields are evaluated eagerly, prior to being passed to the :class:`~string.templatelib.Interpolation` object. For instance, an interpolation of the form ``{amount:.{precision}f}`` will evaluate the inner expression ``{precision}`` to determine the value of the ``format_spec`` attribute. If ``precision`` were to be ``2``, the resulting format specifier would be ``'.2f'``.
String objects have one unique built-in operation: the ``%`` operator (modulo). This is also known as the string *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a string), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language. For example:
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ Otherwise, *values* must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).
Minimum field width (optional). If specified as an ``'*'`` (asterisk), the actual width is read from the next element of the tuple in *values*, and the object to convert comes after the minimum field width and optional precision.
String (converts any Python object using :func:`repr`).
String (converts any Python object using :func:`str`).
String (converts any Python object using :func:`ascii`).
The core built-in types for manipulating binary data are :class:`bytes` and :class:`bytearray`. They are supported by :class:`memoryview` which uses the :ref:`buffer protocol <bufferobjects>` to access the memory of other binary objects without needing to make a copy.
Bytes Objects
Bayt Nesneleri
Bytes objects are immutable sequences of single bytes. Since many major binary protocols are based on the ASCII text encoding, bytes objects offer several methods that are only valid when working with ASCII compatible data and are closely related to string objects in a variety of other ways.
While bytes literals and representations are based on ASCII text, bytes objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that ``0 <= x < 256`` (attempts to violate this restriction will trigger :exc:`ValueError`). This is done deliberately to emphasise that while many binary formats include ASCII based elements and can be usefully manipulated with some text-oriented algorithms, this is not generally the case for arbitrary binary data (blindly applying text processing algorithms to binary data formats that are not ASCII compatible will usually lead to data corruption).
In addition to the literal forms, bytes objects can be created in a number of other ways:
A zero-filled bytes object of a specified length: ``bytes(10)``
This :class:`bytes` class method returns a bytes object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
:meth:`bytes.fromhex` now accepts ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>` as input.
A reverse conversion function exists to transform a bytes object into its hexadecimal representation.
Return a string object containing two hexadecimal digits for each byte in the instance.
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytes objects uses the literal format (``b'...'``) since it is often more useful than e.g. ``bytes([46, 46, 46])``. You can always convert a bytes object into a list of integers using ``list(b)``.
Bytearray Objects
:class:`bytearray` objects are a mutable counterpart to :class:`bytes` objects.
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:
As bytearray objects are mutable, they support the :ref:`mutable <typesseq-mutable>` sequence operations in addition to the common bytes and bytearray operations described in :ref:`bytes-methods`.
This :class:`bytearray` class method returns a bytearray object, decoding the given string object. The string must contain two hexadecimal digits per byte, with ASCII whitespace being ignored.
:meth:`bytearray.fromhex` now accepts ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>` as input.
A reverse conversion function exists to transform a bytearray object into its hexadecimal representation.
Since bytearray objects are sequences of integers (akin to a list), for a bytearray object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytearray object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
The representation of bytearray objects uses the bytes literal format (``bytearray(b'...')``) since it is often more useful than e.g. ``bytearray([46, 46, 46])``. You can always convert a bytearray object into a list of integers using ``list(b)``.
For detailed information on thread-safety guarantees for :class:`bytearray` objects, see :ref:`thread-safety-bytearray`.
Both bytes and bytearray objects support the :ref:`common <typesseq-common>` sequence operations. They interoperate not just with operands of the same type, but with any :term:`bytes-like object`. Due to this flexibility, they can be freely mixed in operations without causing errors. However, the return type of the result may depend on the order of operands.
The methods on bytes and bytearray objects don't accept strings as their arguments, just as the methods on strings don't accept bytes as their arguments. For example, you have to write::
The following methods on bytes and bytearray objects can be used with arbitrary binary data.
The subsequence to search for may be any :term:`bytes-like object` or an integer in the range 0 to 255.
If *sub* is empty, returns the number of empty slices between characters which is the length of the bytes object plus one.
The *prefix* may be any :term:`bytes-like object`.
The bytearray version of this method does *not* operate in place - it always produces a new object, even if no changes were made.
Versi bytearray dari metode ini *tidak* beroperasi di tempatnya - selalu menghasilkan objek baru, bahkan jika tidak ada perubahan yang dilakukan.
The *suffix* may be any :term:`bytes-like object`.
Passing the *encoding* argument to :class:`str` allows decoding any :term:`bytes-like object` directly, without needing to make a temporary :class:`!bytes` or :class:`!bytearray` object.
The suffix(es) to search for may be any :term:`bytes-like object`.
Return a bytes or bytearray object which is the concatenation of the binary data sequences in *iterable*. A :exc:`TypeError` will be raised if there are any values in *iterable* that are not :term:`bytes-like objects <bytes-like object>`, including :class:`str` objects. The separator between elements is the contents of the bytes or bytearray object providing this method.
This static method returns a translation table usable for :meth:`bytes.translate` that will map each character in *from* into the character at the same position in *to*; *from* and *to* must both be :term:`bytes-like objects <bytes-like object>` and have the same length.
Split the sequence at the first occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing a copy of the original sequence, followed by two empty bytes or bytearray objects.
The separator to search for may be any :term:`bytes-like object`.
The subsequence to search for and its replacement may be any :term:`bytes-like object`.
Split the sequence at the last occurrence of *sep*, and return a 3-tuple containing the part before the separator, the separator itself or its bytearray copy, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty bytes or bytearray objects, followed by a copy of the original sequence.
The prefix(es) to search for may be any :term:`bytes-like object`.
Return a copy of the bytes or bytearray object where all bytes occurring in the optional argument *delete* are removed, and the remaining bytes have been mapped through the given translation table, which must be a bytes object of length 256.
The following methods on bytes and bytearray objects have default behaviours that assume the use of ASCII compatible binary formats, but can still be used with arbitrary binary data by passing appropriate arguments. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
Return a copy of the object centered in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
Return a copy of the object left justified in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
The binary sequence of byte values to remove may be any :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method that will remove a single prefix string rather than all of a set of characters. For example::
Return a copy of the object right justified in a sequence of length *width*. Padding is done using the specified *fillbyte* (default is an ASCII space). For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(s)``.
The binary sequence of byte values to remove may be any :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method that will remove a single suffix string rather than all of a set of characters. For example::
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty subsequences (for example, ``b'1,,2'.split(b',')`` returns ``[b'1', b'', b'2']``). The *sep* argument may consist of a multibyte sequence as a single delimiter. Splitting an empty sequence with a specified separator returns ``[b'']`` or ``[bytearray(b'')]`` depending on the type of object being split. The *sep* argument may be any :term:`bytes-like object`.
The binary sequence of byte values to remove may be any :term:`bytes-like object`.
The following methods on bytes and bytearray objects assume the use of ASCII compatible binary formats and should not be applied to arbitrary binary data. Note that all of the bytearray methods in this section do *not* operate in place, and instead produce new objects.
Return a copy of the sequence left filled with ASCII ``b'0'`` digits to make a sequence of length *width*. A leading sign prefix (``b'+'``/ ``b'-'``) is handled by inserting the padding *after* the sign character rather than before. For :class:`bytes` objects, the original sequence is returned if *width* is less than or equal to ``len(seq)``.
Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: the ``%`` operator (modulo). This is also known as the bytes *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a bytes object), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language.
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ Otherwise, *values* must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).
When the right argument is a dictionary (or other mapping type), then the formats in the bytes object *must* include a parenthesised mapping key into that dictionary inserted immediately after the ``'%'`` character. The mapping key selects the value to be formatted from the mapping. For example:
Single byte (accepts integer or single byte objects).
Bytes (any object that follows the :ref:`buffer protocol <bufferobjects>` or has :meth:`~object.__bytes__`).
Bytes (converts any Python object using ``repr(obj).encode('ascii', 'backslashreplace')``).
:class:`memoryview` objects allow Python code to access the internal data of an object that supports the :ref:`buffer protocol <bufferobjects>` without copying.
Create a :class:`memoryview` that references *object*. *object* must support the buffer protocol. Built-in objects that support the buffer protocol include :class:`bytes` and :class:`bytearray`.
A :class:`memoryview` has the notion of an *element*, which is the atomic memory unit handled by the originating *object*. For many simple types such as :class:`bytes` and :class:`bytearray`, an element is a single byte, but other types such as :class:`array.array` may have bigger elements.
If the underlying object is writable, the memoryview supports one-dimensional slice assignment. Resizing is not allowed::
If either format string is not supported by the :mod:`struct` module, then the objects will always compare as unequal (even if the format strings and buffer contents are identical)::
Note that, as with floating-point numbers, ``v is w`` does *not* imply ``v == w`` for memoryview objects.
Return a string object containing two hexadecimal digits for each byte in the buffer. ::
Return a readonly version of the memoryview object. The original memoryview object is unchanged. ::
Release the underlying buffer exposed by the memoryview object. Many objects take special actions when a view is held on them (for example, a :class:`bytearray` would temporarily forbid resizing); therefore, calling release() is handy to remove these restrictions (and free any dangling resources) as soon as possible.
>>> m = memoryview(b'abc') >>> m.release() >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object
>>> with memoryview(b'abc') as m: ... m[0] ... 97 >>> m[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: operation forbidden on released memoryview object
The underlying object of the memoryview::
For information on the thread safety of :class:`memoryview` objects in the :term:`free-threaded build`, see :ref:`thread-safety-memoryview`.
A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. (For other containers see the built-in :class:`dict`, :class:`list`, and :class:`tuple` classes, and the :mod:`collections` module.) See :ref:`time-complexity` for the costs of the various set operations.
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be :term:`hashable`. To represent sets of sets, the inner sets must be :class:`frozenset` objects. If *iterable* is not specified, a new empty set is returned.
Note, the *elem* argument to the :meth:`~object.__contains__`, :meth:`~set.remove`, and :meth:`~set.discard` methods may be a set. In this case, an equivalent frozenset is searched for.
For detailed information on thread-safety guarantees for :class:`set` objects, see :ref:`thread-safety-set`.
A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. There are currently two standard mapping types, the :dfn:`dictionary` and :class:`frozendict`. (For other containers see the built-in :class:`list`, :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module.) See :ref:`time-complexity` for the costs of the various dictionary operations.
A dictionary's keys are *almost* arbitrary values. Values that are not :term:`hashable`, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as ``1``, ``1.0``, and ``True``) can be used interchangeably to index the same dictionary entry.
If no positional argument is given, an empty dictionary is created. If a positional argument is given and it defines a ``keys()`` method, a dictionary is created by calling :meth:`~object.__getitem__` on the argument with each returned key from the method. Otherwise, the positional argument must be an :term:`iterable` object. Each item in the iterable must itself be an iterable with exactly two elements. The first element of each item becomes a key in the new dictionary, and the second element the corresponding value. If a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
If a subclass of dict defines a method :meth:`~object.__missing__` and *key* is not present, the ``d[key]`` operation calls that method with the key *key* as argument. The ``d[key]`` operation then returns or raises whatever is returned or raised by the ``__missing__(key)`` call. No other operations or methods invoke :meth:`~object.__missing__`. If :meth:`~object.__missing__` is not defined, :exc:`KeyError` is raised. :meth:`~object.__missing__` must be a method; it cannot be an instance variable::
:meth:`fromkeys` is a class method that returns a new dictionary. *value* defaults to ``None``. All of the values refer to just a single instance, so it generally doesn't make sense for *value* to be a mutable object such as an empty list. To get distinct values, use a :ref:`dict comprehension <dict>` instead.
Return a new view of the dictionary's items (``(key, value)`` pairs). See the :ref:`documentation of view objects <dict-views>`.
Return a new view of the dictionary's keys. See the :ref:`documentation of view objects <dict-views>`.
:meth:`update` accepts either another object with a ``keys()`` method (in which case :meth:`~object.__getitem__` is called with every key returned from the method) or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: ``d.update(red=1, blue=2)``.
Return a new view of the dictionary's values. See the :ref:`documentation of view objects <dict-views>`.
For detailed information on thread-safety guarantees for :class:`dict` objects, see :ref:`thread-safety-dict`.
Dictionary view objects
The objects returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict.items` are *view objects*. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} >>> keys = dishes.keys() >>> values = dishes.values() >>> # iteration >>> n = 0 >>> for val in values: ... n += val ... >>> print(n) 504 >>> # keys and values are iterated over in the same order (insertion order) >>> list(keys) ['eggs', 'sausage', 'bacon', 'spam'] >>> list(values) [2, 1, 1, 500] >>> # view objects are dynamic and reflect dict changes >>> del dishes['eggs'] >>> del dishes['sausage'] >>> list(keys) ['bacon', 'spam'] >>> # set operations >>> keys & {'eggs', 'bacon', 'salad'} {'bacon'} >>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'} True >>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'} True >>> # get back a read-only proxy for the original dictionary >>> values.mapping mappingproxy({'bacon': 1, 'spam': 500}) >>> values.mapping['spam'] 500
:class:`!frozendict` is not a :class:`!dict` subclass but inherits directly from ``object``.
Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the :keyword:`!as` clause of :keyword:`with` statements using this context manager.
An example of a context manager that returns itself is a :term:`file object`. File objects return themselves from __enter__() to allow :func:`open` to be used as the context expression in a :keyword:`with` statement.
An example of a context manager that returns a related object is the one returned by :func:`decimal.localcontext`. These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the :keyword:`with` statement without affecting code outside the :keyword:`!with` statement.
The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an :meth:`~object.__exit__` method has actually failed.
Python defines several context managers to support easy thread synchronisation, prompt closure of files or other objects, and simpler manipulation of the active decimal arithmetic context. The specific types are not treated specially beyond their implementation of the context management protocol. See the :mod:`contextlib` module for some examples.
Note that there is no specific slot for any of these methods in the type structure for Python objects in the Python/C API. Extension types wanting to define these methods must provide them as a normal Python accessible method. Compared to the overhead of setting up the runtime context, the overhead of a single class dictionary lookup is negligible.
``GenericAlias`` objects are generally created by :ref:`subscripting <subscriptions>` a class. They are most often used with :ref:`container classes <sequence-types>`, such as :class:`list` or :class:`dict`. For example, ``list[int]`` is a ``GenericAlias`` object created by subscripting the ``list`` class with the argument :class:`int`. ``GenericAlias`` objects are intended primarily for use with :term:`type annotations <annotation>`.
It is generally only possible to subscript a class if the class implements the special method :meth:`~object.__class_getitem__`.
A ``GenericAlias`` object acts as a proxy for a :term:`generic type`, implementing *parameterized generics*.
For a container class, the argument(s) supplied to a :ref:`subscription <subscriptions>` of the class may indicate the type(s) of the elements an object contains. For example, ``set[bytes]`` can be used in type annotations to signify a :class:`set` in which all the elements are of type :class:`bytes`.
For a class which defines :meth:`~object.__class_getitem__` but is not a container, the argument(s) supplied to a subscription of the class will often indicate the return type(s) of one or more methods defined on an object. For example, :mod:`regular expressions <re>` can be used on both the :class:`str` data type and the :class:`bytes` data type:
If ``x = re.search('foo', 'foo')``, ``x`` will be a :ref:`re.Match <match-objects>` object where the return values of ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can represent this kind of object in type annotations with the ``GenericAlias`` ``re.Match[str]``.
If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`), ``y`` will also be an instance of ``re.Match``, but the return values of ``y.group(0)`` and ``y[0]`` will both be of type :class:`bytes`. In type annotations, we would represent this variety of :ref:`re.Match <match-objects>` objects with ``re.Match[bytes]``.
``GenericAlias`` objects are instances of the class :class:`types.GenericAlias`, which can also be used to create ``GenericAlias`` objects directly. Specializations of user-defined :ref:`generic classes <generic-classes>` may not be instances of :class:`types.GenericAlias`, but they provide similar functionality.
Another example for :term:`mapping` objects, using a :class:`dict`, which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects a ``dict`` with keys of type :class:`str` and values of type :class:`int`::
The Python runtime does not enforce :term:`type annotations <annotation>`. This extends to generic types and their type parameters. When creating a container object from a ``GenericAlias``, the elements in the container are not checked against their type. For example, the following code is discouraged, but will run without errors::
Furthermore, parameterized generics erase type parameters during object creation::
The :meth:`~object.__getitem__` method of generic containers will raise an exception to disallow mistakes like ``dict[str][str]``::
However, such expressions are valid when :ref:`type variables <generics>` are used. The index must have as many elements as there are type variable items in the ``GenericAlias`` object's :attr:`~genericalias.__args__`. ::
:ref:`re.Pattern <re-objects>`
:ref:`re.Match <match-objects>`
Special Attributes of ``GenericAlias`` objects
This attribute is a :class:`tuple` (possibly of length 1) of generic types passed to the original :meth:`~object.__class_getitem__` of the generic class::
A ``GenericAlias`` object with :class:`typing.ParamSpec` parameters may not have correct ``__parameters__`` after substitution because :class:`typing.ParamSpec` is intended primarily for static type checking.
Introducing the ability to natively parameterize standard-library classes, provided they implement the special class method :meth:`~object.__class_getitem__`.
A union object holds the value of the ``|`` (bitwise or) operation on multiple :ref:`type objects <bltin-type-objects>`. These types are intended primarily for :term:`type annotations <annotation>`. The union type expression enables cleaner type hinting syntax compared to subscripting :class:`typing.Union`.
Defines a union object which holds types *X*, *Y*, and so forth. ``X | Y`` means either X or Y. It is equivalent to ``typing.Union[X, Y]``. For example, the following function expects an argument of type :class:`int` or :class:`float`::
Union objects can be tested for equality with other union objects. Details:
Calls to :func:`isinstance` and :func:`issubclass` are also supported with a union object::
However, :ref:`parameterized generics <types-genericalias>` in union objects cannot be checked::
The user-exposed type for the union object can be accessed from :class:`typing.Union` and used for :func:`isinstance` checks::
The :meth:`!__or__` method for type objects was added to support the syntax ``X | Y``. If a metaclass implements :meth:`!__or__`, it may override the default behavior of creating a union:
Union objects are now instances of :class:`typing.Union`. Previously, they were instances of :class:`types.UnionType`, which remains an alias for :class:`typing.Union`.
The interpreter supports several other kinds of objects. Most of these support only one or two operations.
The only special operation on a module is attribute access: ``m.name``, where *m* is a module and *name* accesses a name defined in *m*'s symbol table. Module attributes can be assigned to. (Note that the :keyword:`import` statement is not, strictly speaking, an operation on a module object; ``import foo`` does not require a module object named *foo* to exist, rather it requires an (external) *definition* for a module named *foo* somewhere.)
A special attribute of every module is :attr:`~object.__dict__`. This is the dictionary containing the module's symbol table. Modifying this dictionary will actually change the module's symbol table, but direct assignment to the :attr:`~object.__dict__` attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying :attr:`~object.__dict__` directly is not recommended.
See :ref:`objects` and :ref:`class` for these.
Function objects are created by function definitions. The only operation on a function object is to call it: ``func(argument-list)``.
There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types.
If you access a method (a function defined in a class namespace) through an instance, you get a special object: a :dfn:`bound method` (also called :ref:`instance method <instance-methods>`) object. When called, it will add the ``self`` argument to the argument list. Bound methods have two special read-only attributes: :attr:`m.__self__ <method.__self__>` is the object on which the method operates, and :attr:`m.__func__ <method.__func__>` is the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)`` is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)``.
Like :ref:`function objects <user-defined-funcs>`, bound method objects support getting arbitrary attributes. However, since method attributes are actually stored on the underlying function object (:attr:`method.__func__`), setting method attributes on bound methods is disallowed. Attempting to set an attribute on a method results in an :exc:`AttributeError` being raised. In order to set a method attribute, you need to explicitly set it on the underlying function object:
>>> class C: ... def method(self): ... pass ... >>> c = C() >>> c.method.whoami = 'my name is method' # can't set on the method Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'method' object has no attribute 'whoami' >>> c.method.__func__.whoami = 'my name is method' >>> c.method.whoami 'my name is method'
Code Objects
Objek Kode
Code objects are used by the implementation to represent "pseudo-compiled" executable Python code such as a function body. They differ from function objects because they don't contain a reference to their global execution environment. Code objects are returned by the built-in :func:`compile` function and can be extracted from function objects through their :attr:`~function.__code__` attribute. See also the :mod:`code` module.
Accessing :attr:`~function.__code__` raises an :ref:`auditing event <auditing>` ``object.__getattr__`` with arguments ``obj`` and ``"__code__"``.
A code object can be executed or evaluated by passing it (instead of a source string) to the :func:`exec` or :func:`eval` built-in functions.
Type Objects
Objek Tipe
Type objects represent the various object types. An object's type is accessed by the built-in function :func:`type`. There are no special operations on types. The standard module :mod:`types` defines names for all standard built-in types.
The Null Object
This object is returned by functions that don't explicitly return a value. It supports no special operations. There is exactly one null object, named ``None`` (a built-in name). ``type(None)()`` produces the same singleton.
The Ellipsis Object
This object is commonly used to indicate that something is omitted. It supports no special operations. There is exactly one ellipsis object, named :const:`Ellipsis` (a built-in name). ``type(Ellipsis)()`` produces the :const:`Ellipsis` singleton.
In typical use, ``...`` as the ``Ellipsis`` object appears in a few different places, for instance:
Python also uses three dots in ways that are not ``Ellipsis`` objects, for instance:
The NotImplemented Object
This object is returned from comparisons and binary operations when they are asked to operate on types they don't support. See :ref:`comparisons` for more information. There is exactly one :data:`NotImplemented` object. :code:`type(NotImplemented)()` produces the singleton instance.
Internal Objects
See :ref:`types` for this information. It describes :ref:`stack frame objects <frame-objects>`, :ref:`traceback objects <traceback-objects>`, and slice objects.
The implementation adds a few special read-only attributes to several object types, where they are relevant. Some of these are not reported by the :func:`dir` built-in function.
None (Built-in object)
False (Built-in object)
object
objek
objects
code object
objek kode
__code__ (function object attribute)