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`.
empty sequences and collections: ``''``, ``()``, ``[]``, ``{}``, ``set()``, ``range(0)``
urutan dan koleksi kosong: ``''``, ``()``, ``[]``, ``{}``, ``set()``, ``range(0)``
There are eight comparison operations in Python. They all have the same priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and y <= z``, except that *y* is evaluated only once (but in both cases *z* is not evaluated at all when ``x < y`` is found to be false).
Ada delapan operasi perbandingan di Python. Mereka semua memiliki prioritas yang sama (yang lebih tinggi dari operasi *Boolean*). Perbandingan dapat dirantai secara berubah-ubah; misalnya, ``x < y <= z`` setara dengan ``x < y and y <= z``, kecuali bahwa *y* dievaluasi hanya sekali (tetapi dalam kedua kasus *z* tidak dievaluasi sama sekali ketika ``x < y`` ditemukan bernilai salah).
Equivalent to::
Setara dengan::
For backwards compatibility, however, the second signature is supported, following a convention from older versions of Python. The *type* argument should be an exception class, and *value* should be an exception instance. If the *value* is not provided, the *type* constructor is called to get an instance. If *traceback* is provided, it is set on the exception, otherwise any existing :attr:`~BaseException.__traceback__` attribute stored in *value* may be cleared.
This support allows immutable sequences, such as :class:`tuple` instances, to be used as :class:`dict` keys and stored in :class:`set` and :class:`frozenset` instances.
*reverse* is a boolean value. If set to ``True``, then the list elements are sorted as if each comparison were reversed.
*reverse* adalah nilai *boolean*. Jika diatur ke ``True``, maka elemen list atau daftar diurutkan seolah-olah setiap perbandingan dibalik.
Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the :func:`enumerate` built-in). Tuples are also used for cases where an immutable sequence of homogeneous data is needed (such as allowing storage in a :class:`set` or :class:`dict` instance).
Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every *tabsize* characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (``\t``), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (``\n``) or return (``\r``), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed. For example::
When formatting a number (:class:`int`, :class:`float`, :class:`complex`, :class:`decimal.Decimal` and subclasses) with the ``n`` type (ex: ``'{:n}'.format(1234)``), the function temporarily sets the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale to decode ``decimal_point`` and ``thousands_sep`` fields of :c:func:`localeconv` if they are non-ASCII or longer than 1 byte, and the ``LC_NUMERIC`` locale is different than the ``LC_CTYPE`` locale. This temporary change affects other threads.
When formatting a number with the ``n`` type, the function sets temporarily the ``LC_CTYPE`` locale to the ``LC_NUMERIC`` locale in some cases.
Return a copy of the string with leading characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix; rather, all combinations of its values are stripped::
See :meth:`str.removeprefix` for a method that will remove a single prefix string rather than all of a set of characters. For example::
>>> 'TestHook'.removeprefix('Test') 'Hook' >>> 'BaseTestCase'.removeprefix('Test') 'BaseTestCase'
Return a copy of the string with trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a suffix; rather, all combinations of its values are stripped. For example:
See :meth:`removesuffix` for a method that will remove a single suffix string rather than all of a set of characters. For example::
This method splits on the following line boundaries. In particular, the boundaries are a superset of :term:`universal newlines`.
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped.
The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end.
When the equals sign ``'='`` is provided in an interpolation expression, the text of the expression is appended to the literal string that precedes the relevant interpolation. This includes the equals sign and any surrounding whitespace. The :class:`!Interpolation` instance for the expression will be created as normal, except that :attr:`~string.templatelib.Interpolation.conversion` will be set to '``r``' (:func:`repr`) by default. If an explicit conversion or format specifier is provided, this will override the default behaviour.
If the :class:`bytearray` needs to grow, all new bytes will be set to null bytes.
>>> b'TestHook'.removeprefix(b'Test') b'Hook' >>> b'BaseTestCase'.removeprefix(b'Test') b'BaseTestCase'
Set the *table* argument to ``None`` for translations that only delete characters::
Return a copy of the sequence with specified leading bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a prefix; rather, all combinations of its values are stripped::
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 sequence with specified trailing bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a suffix; rather, all combinations of its values are stripped::
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::
Return a copy of the sequence with specified leading and trailing bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a prefix or suffix; rather, all combinations of its values are stripped::
Return a copy of the sequence where all ASCII tab characters are replaced by one or more ASCII spaces, depending on the current column and the given tab size. Tab positions occur every *tabsize* bytes (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the sequence, the current column is set to zero and the sequence is examined byte by byte. If the byte is an ASCII tab character (``b'\t'``), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the current byte is an ASCII newline (``b'\n'``) or carriage return (``b'\r'``), it is copied and the current column is reset to zero. Any other byte value is copied unchanged and the current column is incremented by one regardless of how the byte value is represented when printed::
For the subset of :mod:`struct` format strings currently supported by :meth:`tolist`, ``v`` and ``w`` are equal if ``v.tolist() == w.tolist()``::
Set Types --- :class:`set`, :class:`frozenset`
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.
Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in set``. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.
There are currently two built-in set types, :class:`set` and :class:`frozenset`. The :class:`set` type is mutable --- the contents can be changed using methods like :meth:`~set.add` and :meth:`~set.remove`. Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set. The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
Non-empty sets (not frozensets) can be created by placing a comma-separated list of elements within braces, for example: ``{'jack', 'sjoerd'}``, in addition to the :class:`set` constructor.
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.
Sets can be created by several means:
Use a set comprehension: ``{c for c in 'abracadabra' if c not in 'abc'}``
Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
Instances of :class:`set` and :class:`frozenset` provide the following operations:
Return the number of elements in set *s* (cardinality of *s*).
Return ``True`` if the set has no elements in common with *other*. Sets are disjoint if and only if their intersection is the empty set.
Test whether every element in the set is in *other*.
Test whether the set is a proper subset of *other*, that is, ``set <= other and set != other``.
Test whether every element in *other* is in the set.
Test whether the set is a proper superset of *other*, that is, ``set >= other and set != other``.
Return a new set with elements from the set and all others.
Return a new set with elements common to the set and all others.
Return a new set with elements in the set that are not in the others.
Return a new set with elements in either the set or *other* but not both.
Return a shallow copy of the set.
Note, the non-operator versions of :meth:`~frozenset.union`, :meth:`~frozenset.intersection`, :meth:`~frozenset.difference`, :meth:`~frozenset.symmetric_difference`, :meth:`~frozenset.issubset`, and :meth:`~frozenset.issuperset` methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like ``set('abc') & 'cbs'`` in favor of the more readable ``set('abc').intersection('cbs')``.
Both :class:`set` and :class:`frozenset` support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).
Instances of :class:`set` are compared to instances of :class:`frozenset` based on their members. For example, ``set('abc') == frozenset('abc')`` returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so *all* of the following return ``False``: ``a<b``, ``a==b``, or ``a>b``.
Since sets only define partial ordering (subset relationships), the output of the :meth:`list.sort` method is undefined for lists of sets.
Set elements, like dictionary keys, must be :term:`hashable`.
Binary operations that mix :class:`set` instances with :class:`frozenset` return the type of the first operand. For example: ``frozenset('ab') | set('bc')`` returns an instance of :class:`frozenset`.
The following table lists operations available for :class:`set` that do not apply to immutable instances of :class:`frozenset`:
Update the set, adding elements from all others.
Update the set, keeping only elements found in it and all others.
Update the set, removing elements found in others.
Update the set, keeping only elements found in either set, but not in both.
Add element *elem* to the set.
Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is not contained in the set.
Remove element *elem* from the set if it is present.
Remove and return an arbitrary element from the set. Raises :exc:`KeyError` if the set is empty.
Remove all elements from the set.
Note, the non-operator versions of the :meth:`~set.update`, :meth:`~set.intersection_update`, :meth:`~set.difference_update`, and :meth:`~set.symmetric_difference_update` methods will accept any iterable as an argument.
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.
Sets and frozensets are :ref:`generic <generics>` over the type of their elements.
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.
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
Set ``d[key]`` to *value*.
Create a new dictionary with keys from *iterable* and values set to *value*.
:meth:`popitem` is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling :meth:`popitem` raises a :exc:`KeyError`.
Keys views are set-like since their entries are unique and :term:`hashable`. Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class :class:`collections.abc.Set` are available (for example, ``==``, ``<``, or ``^``). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.
>>> 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
Return a new frozen dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.
:meth:`!__setitem__`
:meth:`~dict.setdefault`
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.
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.
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`.
:class:`set`
:class:`frozenset`
:class:`collections.abc.Set`
:class:`collections.abc.MutableSet`
:class:`weakref.WeakSet`
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'
>>> import sys >>> sys.set_int_max_str_digits(4300) # Illustrative, this is the default. >>> _ = int('2' * 5432) Traceback (most recent call last): ... ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5432 digits; use sys.set_int_max_str_digits() to increase the limit >>> i = int('2' * 4300) >>> len(str(i)) 4300 >>> i_squared = i*i >>> len(str(i_squared)) Traceback (most recent call last): ... ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit >>> len(hex(i_squared)) 7144 >>> assert int(hex(i_squared), base=16) == i*i # Hexadecimal is unlimited.
:envvar:`PYTHONINTMAXSTRDIGITS`, e.g. ``PYTHONINTMAXSTRDIGITS=640 python3`` to set the limit to 640 or ``PYTHONINTMAXSTRDIGITS=0 python3`` to disable the limitation.
:data:`sys.flags.int_max_str_digits` contains the value of :envvar:`PYTHONINTMAXSTRDIGITS` or :option:`-X int_max_str_digits <-X>`. If both the env var and the ``-X`` option are set, the ``-X`` option takes precedence. A value of *-1* indicates that both were unset, thus a value of :data:`sys.int_info.default_max_str_digits` was used during initialization.
From code, you can inspect the current limit and set a new one using these :mod:`sys` APIs:
:func:`sys.get_int_max_str_digits` and :func:`sys.set_int_max_str_digits` are a getter and setter for the interpreter-wide limit. Subinterpreters have their own limit.
Setting a low limit *can* lead to problems. While rare, code exists that contains integer constants in decimal in their source that exceed the minimum threshold. A consequence of setting the limit is that Python source code containing decimal integer literals longer than the limit will encounter an error during parsing, usually at startup time or import time or even at installation time - anytime an up to date ``.pyc`` does not already exist for the code. A workaround for source that contains such large constants is to convert them to ``0x`` hexadecimal form as it has no limit.
Test your application thoroughly if you use a low limit. Ensure your tests run with the limit set early via the environment or flag so that it applies during startup and even during any installation step that may invoke Python to precompile ``.py`` sources to ``.pyc`` files.
The default :data:`sys.int_info.default_max_str_digits` is expected to be reasonable for most applications. If your application requires a different limit, set it from your main entry point using Python version agnostic code as these APIs were added in security patch releases in versions before 3.12.
>>> import sys >>> if hasattr(sys, "set_int_max_str_digits"): ... upper_bound = 68000 ... lower_bound = 4004 ... current_limit = sys.get_int_max_str_digits() ... if current_limit == 0 or current_limit > upper_bound: ... sys.set_int_max_str_digits(upper_bound) ... elif current_limit < lower_bound: ... sys.set_int_max_str_digits(lower_bound)
If you need to disable it entirely, set it to ``0``.
set
set