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
Built-in Types
Tipe Bawaan
The following sections describe the standard types that are built into the interpreter.
Bagian berikut menjelaskan tipe standar yang dibangun ke dalam *interpreter*.
The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions.
Tipe bawaan utama adalah angka, urutan, pemetaan, kelas, *instance*, dan pengecualian.
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`.
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.
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).
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.
Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
There are three distinct numeric types: :dfn:`integers`, :dfn:`floating-point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a subtype of integers. Integers have unlimited precision. Floating-point numbers are usually implemented using :c:expr:`double` in C; information about the precision and internal representation of floating-point numbers for the machine on which your program is running is available in :data:`sys.float_info`. Complex numbers have a real and imaginary part, which are each a floating-point number. To extract these parts from a complex number *z*, use ``z.real`` and ``z.imag``. (The standard library includes the additional numeric types :mod:`fractions.Fraction`, for rationals, and :mod:`decimal.Decimal`, for floating-point numbers with user-definable precision.)
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different built-in numeric types, the operand with the "narrower" type is widened to that of the other:
A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. [2]_
All numeric types (except complex) support the following operations (for priorities of the operations, see :ref:`operator-summary`):
All :class:`numbers.Real` types (:class:`int` and :class:`float`) also include the following operations:
Bitwise Operations on Integer Types
Additional Methods on Integer Types
Hashing of numeric types
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`.
:class:`bool` is a subclass of :class:`int` (see :ref:`typesnumeric`). In many numeric contexts, ``False`` and ``True`` behave like the integers 0 and 1, respectively. However, relying on this is discouraged; explicitly convert using :func:`int` instead.
Iteration-related types
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.
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.
Generator types
Generator iterators implement the :ref:`iterator protocol <stdtypes-iterators>`. Iterating them drives execution of the underlying generator function.
Sequence Types --- :class:`list`, :class:`tuple`, :class:`range`
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.
The operations in the following table are supported by most sequence types, both mutable and immutable. The :class:`collections.abc.Sequence` ABC is provided to make it easier to correctly implement these operations on custom sequence types.
for other types, investigate the relevant class documentation
Some sequence types (such as :class:`range`) only support item sequences that follow specific patterns, and hence don't support sequence concatenation or repetition.
Sequence types also support the following methods:
Not all sequence types support passing the *start* and *stop* arguments.
Immutable Sequence Types
The only operation that immutable sequence types generally implement that is not also implemented by mutable sequence types is support for the :func:`hash` built-in.
Mutable Sequence Types
The operations in the following table are defined on mutable sequence types. The :class:`collections.abc.MutableSequence` ABC is provided to make it easier to correctly implement these operations on custom sequence types.
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`.
Mutable sequence types also support the following methods:
The :meth:`!copy` method is not part of the :class:`~collections.abc.MutableSequence` :class:`~abc.ABC`, but most concrete mutable sequence types provide it.
Lists are :ref:`generic <generics>` over the types of their items.
Lists implement all of the :ref:`common <typesseq-common>` and :ref:`mutable <typesseq-mutable>` sequence operations. Lists also provide the following additional method:
Tuples implement all of the :ref:`common <typesseq-common>` sequence operations.
Tuples are :ref:`generic <generics>` over the types of their contents. For more information, refer to :ref:`the typing documentation on annotating tuples <annotating-tuples>`.
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).
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`):
The following table summarizes the text and binary sequence types methods by category.
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 implement all of the :ref:`common <typesseq-common>` sequence operations, along with the additional methods described below.
Strings also support two styles of string formatting, one providing a large degree of flexibility and customization (see :meth:`str.format`, :ref:`formatstrings` and :ref:`string-formatting`) and the other based on C ``printf`` style formatting that handles a narrower range of types and is slightly harder to use correctly, but is often faster for the cases it can handle (:ref:`old-string-formatting`).
Here "printable" means the character is suitable for :func:`repr` to use in its output; "non-printable" means that :func:`repr` on built-in types will hex-escape the character. It has no bearing on the handling of strings written to :data:`sys.stdout` or :data:`sys.stderr`.
These strings follow the same syntax and evaluation rules as :ref:`formatted string literals <stdtypes-fstrings>`, with the following differences:
>>> print('%s has %d quote types.' % ('Python', 2)) Python has 2 quote types.
Conversion flags (optional), which affect the result of some conversion types.
The conversion types are:
Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview`
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.
The :mod:`array` module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values.
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`.
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.
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.
One-dimensional memoryviews of :term:`hashable` (read-only) types with formats 'B', 'b' or 'c' are also hashable. The hash is defined as ``hash(m) == hash(m.tobytes())``::
>>> from ctypes import BigEndianStructure, c_long >>> class BEPoint(BigEndianStructure): ... _fields_ = [("x", c_long), ("y", c_long)] ... >>> point = BEPoint(100, 200) >>> a = memoryview(point) >>> b = memoryview(point) >>> a == point False >>> a == b False
Set Types --- :class:`set`, :class:`frozenset`
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.
Mapping types --- :class:`!dict`, :class:`!frozendict`
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.
Dictionaries are :ref:`generic <generics>` over two types, signifying (respectively) the types of the dictionary's keys and values.
These are the operations that dictionaries support (and therefore, custom mapping types should support too):
:class:`types.MappingProxyType` can be used to create a read-only view of a :class:`dict`. :class:`frozendict` is an immutable version of :class:`dict`.
Return a :class:`types.MappingProxyType` that wraps the original dictionary to which the view refers.
Like dictionaries, frozendicts are :ref:`generic <generics>` over two types, signifying (respectively) the types of the frozendict's keys and values.
Context Manager Types
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.
Type Annotation Types --- :ref:`Generic Alias <types-genericalias>`, :ref:`Union <types-union>`
The core built-in types for :term:`type annotations <annotation>` are :ref:`Generic Alias <types-genericalias>` and :ref:`Union <types-union>`.
``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>`.
``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.
Creates a ``GenericAlias`` representing a type ``T`` parameterized by types *X*, *Y*, and more depending on the ``T`` used. For example, a function expecting a :class:`list` containing :class:`float` elements::
The builtin functions :func:`isinstance` and :func:`issubclass` do not accept ``GenericAlias`` types for their second argument::
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::
>>> t = list[str] >>> type(t) <class 'types.GenericAlias'> >>> l = t() >>> type(l) <class 'list'>
:class:`types.MappingProxyType`
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 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`::
Redundant types are removed::
Optional types can be spelled as a union with ``None``::
However, :ref:`parameterized generics <types-genericalias>` in union objects cannot be checked::
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`.
Other Built-in Types
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.
Methods are functions that are called using the attribute notation. There are two flavors: :ref:`built-in methods <builtin-methods>` (such as :meth:`~list.append` on lists) and :ref:`class instance methods <instance-methods>`. Built-in methods are described with the types that support them.
See :ref:`types` for more information.
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.
Types are written like this: ``<class 'int'>``.
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.
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.
types
types
binary sequence types