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`.
zero of any numeric type: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, ``Fraction(0, 1)``
nol dari semua tipe numerik: ``0``, ``0.0``, ``0j``, ``Decimal(0)``, ``Fraction(0, 1)``
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.)
The constructors :func:`int`, :func:`float`, and :func:`complex` can be used to produce numbers of a specific type.
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`):
Also referred to as integer division. For operands of type :class:`int`, the result has type :class:`int`. For operands of type :class:`float`, the result has type :class:`float`. In general, the result is a whole integer, though the result's type is not necessarily :class:`int`. The result is always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
See `the Unicode Standard <https://unicode.org/Public/UNIDATA/extracted/DerivedNumericType.txt>`_ for a complete list of code points with the ``Nd`` property.
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
The int type implements the :class:`numbers.Integral` :term:`abstract base class`. In addition, it provides a few more methods:
Returns ``True``. Exists for duck type compatibility with :meth:`float.is_integer`.
The float type implements the :class:`numbers.Real` :term:`abstract base class`. float also has the following additional methods.
The :class:`!complex` type implements the :class:`numbers.Complex` :term:`abstract base class`. :class:`!complex` also has the following additional methods.
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`.
Boolean Type - :class:`bool`
Booleans represent truth values. The :class:`bool` type has exactly two constant instances: ``True`` and ``False``.
: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.
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.
Generator types
Generator iterators implement the :ref:`iterator protocol <stdtypes-iterators>`. Iterating them drives execution of the underlying generator function.
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.
The second signature \(type\[, value\[, traceback\]\]\) is deprecated and may be removed in a future version of Python.
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.
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*.
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length. (For full details see :ref:`comparisons` in the language reference.)
Values of *n* less than ``0`` are treated as ``0`` (which yields an empty sequence of the same type as *s*). Note that items in the sequence *s* are not copied; they are referenced multiple times. This often haunts new Python programmers; consider::
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.
Attempting to hash an immutable sequence that contains unhashable values will result in :exc:`TypeError`.
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.
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`.
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.
Using the type constructor: ``list()`` or ``list(iterable)``
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>`.
The :class:`range` type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in :keyword:`for` loops.
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`):
Text and Binary Sequence Type Methods Summary
The following table summarizes the text and binary sequence types methods by category.
Text Sequence Type --- :class:`str`
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:
Since there is no separate "character" type, indexing a string produces strings of length 1. That is, for a non-empty string *s*, ``s[0] == s[0:1]``.
There is also no mutable string type, but :meth:`str.join` or :class:`io.StringIO` can be used to efficiently construct strings from multiple fragments.
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>`.
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`).
>>> encoded_str_to_bytes = 'Python'.encode() >>> type(encoded_str_to_bytes) <class 'bytes'> >>> encoded_str_to_bytes b'Python'
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 ``True`` if all characters in the string are digits and there is at least one character, ``False`` otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the `Kharosthi numbers <https://en.wikipedia.org/wiki/Kharosthi#Numerals>`__. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
Return ``True`` if all characters in the string are numeric characters, and there is at least one character, ``False`` otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric. For example:
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`.
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:
An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is a string literal that is prefixed with ``f`` or ``F``. This type of string literal allows embedding the results of arbitrary Python expressions within *replacement fields*, which are delimited by curly brackets (``{}``). Each replacement field must contain an expression, optionally followed by:
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.
Conversion type.
When the right argument is a dictionary (or other mapping type), then the formats in the string *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:
The conversion types are:
Obsolete type -- it is identical to ``'d'``.
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.
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytes type has an additional class method to read data in that format:
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`.
Since 2 hexadecimal digits correspond precisely to a single byte, hexadecimal numbers are a commonly used format for describing binary data. Accordingly, the bytearray type has an additional class method to read data in that format:
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.
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.
Split the binary sequence into subsequences of the same type, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* ones. If *sep* is not specified or ``None``, any subsequence consisting solely of :meth:`ASCII whitespace <bytes.isspace>` is a separator. Except for splitting from the right, :meth:`rsplit` behaves like :meth:`split` which is described in detail below.
Split the binary sequence into subsequences of the same type, using *sep* as the delimiter string. If *maxsplit* is given and non-negative, at most *maxsplit* splits are done (thus, the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not specified or is ``-1``, then there is no limit on the number of splits (all possible splits are made).
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`.
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:
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.
:class:`!memoryview`\s are :ref:`generic <generics>` over the type of their underlying data.
If ``view.ndim == 0``, ``len(view)`` now raises :exc:`TypeError` instead of returning 1.
If :class:`~memoryview.format` is one of the native format specifiers from the :mod:`struct` module, indexing with an integer or a tuple of integers is also supported and returns a single *element* with the correct type. One-dimensional memoryviews can be indexed with an integer or a one-integer tuple. Multi-dimensional memoryviews can be indexed with tuples of exactly *ndim* integers where *ndim* is the number of dimensions. Zero-dimensional memoryviews can be indexed with the empty tuple.
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())``::
memoryview is now a :term:`generic type`.
>>> 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
>>> m = memoryview(bytearray(b'abc')) >>> mm = m.toreadonly() >>> mm.tolist() [97, 98, 99] >>> mm[0] = 42 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot modify read-only memory >>> m[0] = 43 >>> mm.tolist() [43, 98, 99]
>>> b = bytearray(b'zyz') >>> x = memoryview(b) >>> x[0] = b'a' Traceback (most recent call last): ... TypeError: memoryview: invalid type for format 'B' >>> y = x.cast('c') >>> y[0] = b'a' >>> b bytearray(b'ayz')
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.
Use the type constructor: ``set()``, ``set('foobar')``, ``set(['a', 'b', 'foo'])``
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`.
Sets and frozensets are :ref:`generic <generics>` over the type of their elements.
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.
Use the type constructor: ``dict()``, ``dict([('foo', 100), ('bar', 200)])``, ``dict(foo=100, bar=200)``
Dictionaries compare equal if and only if they have the same ``(key, value)`` pairs (regardless of ordering). Order comparisons ('<', '<=', '>=', '>') raise :exc:`TypeError`. To illustrate dictionary creation and equality, the following examples all return a dictionary equal to ``{"one": 1, "two": 2, "three": 3}``::
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.
Similar to :meth:`dict.fromkeys`, but call again the type constructor with an initialized :class:`frozendict` if the type is a :class:`frozendict` subclass.
Context Manager Types
Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the :keyword:`with` statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are ``None``.
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>`.
Generic Alias Type
``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>`.
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.
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::
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 builtin functions :func:`isinstance` and :func:`issubclass` do not accept ``GenericAlias`` types for their second argument::
>>> isinstance([1, 2], list[str]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: isinstance() argument 2 cannot be a parameterized generic
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::
>>> t = list[str] >>> type(t) <class 'types.GenericAlias'> >>> l = t() >>> type(l) <class 'list'>
Calling :func:`repr` or :func:`str` on a generic shows the parameterized type::
>>> dict[str][str] Traceback (most recent call last): ... TypeError: dict[str] is not a generic class
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__`. ::
>>> from typing import TypeVar >>> Y = TypeVar('Y') >>> dict[str, Y][int] dict[str, int]
:class:`type`
: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::
This attribute is a lazily computed tuple (possibly empty) of unique type variables found in ``__args__``::
>>> from typing import TypeVar >>> T = TypeVar('T') >>> list[T].__parameters__ (~T,)
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.
A boolean that is true if the alias has been unpacked using the ``*`` operator (see :data:`~typing.TypeVarTuple`).
:pep:`484` - Type Hints
Introducing Python's framework for type annotations.
:pep:`585` - Type Hinting Generics In Standard Collections
Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.
Union Type
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::
int | str == typing.Union[int, str] type(int | str) is typing.Union
Optional types can be spelled as a union with ``None``::
However, :ref:`parameterized generics <types-genericalias>` in union objects cannot be checked::
>>> isinstance(1, int | list[int]) # short-circuit evaluation True >>> isinstance([1], int | list[int]) Traceback (most recent call last): ... TypeError: isinstance() argument 2 cannot be a parameterized generic
The user-exposed type for the union object can be accessed from :class:`typing.Union` and used for :func:`isinstance` checks::
>>> import typing >>> isinstance(int | str, typing.Union) True >>> typing.Union() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: cannot create 'typing.Union' instances
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:
>>> class M(type): ... def __or__(self, other): ... return "Hello" ... >>> class C(metaclass=M): ... pass ... >>> C | int 'Hello' >>> int | C int | C
:pep:`604` -- PEP proposing the ``X | Y`` syntax and the Union type.
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
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.
Types are written like this: ``<class 'int'>``.
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.
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 type annotations, such as :ref:`callable arguments <annotating-callables>` or :ref:`tuple elements <annotating-tuples>`.
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.
The :ref:`type parameters <type-params>` of generic classes, functions, and :ref:`type aliases <type-aliases>`. For classes and functions that are not generic, this will be an empty tuple.
The :class:`int` type in CPython is an arbitrary length number stored in binary form (commonly known as a "bignum"). There exists no algorithm that can convert a string to a binary integer or a binary integer to a string in linear time, *unless* the base is a power of 2. Even the best known algorithms for base 10 have sub-quadratic complexity. Converting a large value such as ``int('1' * 500_000)`` can take over a second on a fast CPU.
They must have since the parser can't tell the type of the operands.
types
types
type
tipe
text sequence type
binary sequence types
type annotation; type hint