Pelokalan
Python ID
id en
Masuk
Proyek
reference__datamodel.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
Objects, values and types
Every object has an identity, a type and a value. An object's *identity* never changes once it has been created; you may think of it as the object's address in memory. The :keyword:`is` operator compares the identity of two objects; the :func:`id` function returns an integer representing its identity.
An object's type determines the operations that the object supports (e.g., "does it have a length?") and also defines the possible values for objects of that type. The :func:`type` function returns an object's type (which is an object itself). Like its identity, an object's :dfn:`type` is also unchangeable. [#]_
The *value* of some objects can change. Objects whose value can change are said to be *mutable*; objects whose value is unchangeable once they are created are called *immutable*. (The value of an immutable container object that contains a reference to a mutable object can change when the latter's value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object's mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. For example, after ``a = 1; b = 1``, *a* and *b* may or may not refer to the same object with the value one, depending on the implementation. This is because :class:`int` is an immutable type, so the reference to ``1`` can be reused. This behaviour depends on the implementation used, so should not be relied upon, but is something to be aware of when making use of object identity tests. However, after ``c = []; d = []``, *c* and *d* are guaranteed to refer to two different, unique, newly created empty lists. (Note that ``e = f = []`` assigns the *same* object to both *e* and *f*.)
The standard type hierarchy
Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead.
Some of the type descriptions below contain a paragraph listing 'special attributes.' These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future.
This type has a single value. There is a single object with this value. This object is accessed through the built-in name ``None``. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don't explicitly return anything. Its truth value is false.
This type has a single value. There is a single object with this value. This object is accessed through the built-in name :data:`NotImplemented`. Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) It should not be evaluated in a boolean context.
Evaluating :data:`NotImplemented` in a boolean context now raises a :exc:`TypeError`. It previously evaluated to :const:`True` and emitted a :exc:`DeprecationWarning` since Python 3.9.
This type has a single value. There is a single object with this value. This object is accessed through the literal ``...`` or the built-in name ``Ellipsis``. Its truth value is true.
There are two types of integers:
These represent the truth values False and True. The two objects representing the values ``False`` and ``True`` are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings ``"False"`` or ``"True"`` are returned, respectively.
Sequences also support slicing: ``a[start:stop]`` selects all items with index *k* such that *start* ``<=`` *k* ``<`` *stop*. When used as an expression, a slice is a sequence of the same type. The comment above about negative subscripts also applies to negative slice positions. Note that no error is raised if a slice position is less than zero or larger than the length of the sequence.
An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)
The following types are immutable sequences:
Python doesn't have a dedicated *character* type. Instead, every code point in the string is represented as a string object with length ``1``.
The :mod:`collections` and :mod:`array` module provide additional examples of mutable sequence types.
There are currently two intrinsic mutable sequence types:
Set types
For set elements, the same immutability rules apply as for dictionary keys. Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a set.
There are currently two intrinsic set types:
There are two intrinsic mapping types:
These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key's hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index the same dictionary entry.
The extension modules :mod:`dbm.ndbm` and :mod:`dbm.gnu` provide additional examples of mapping types, as does the :mod:`collections` module.
Callable types
These are the types to which the function call operation (see section :ref:`calls`) can be applied:
Most of these attributes check the type of the assigned value:
A :class:`tuple` containing the :ref:`type parameters <type-params>` of a :ref:`generic function <generic-functions>`.
A built-in function object is a wrapper around a C function. Examples of built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes:
Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override :meth:`~object.__new__`. The arguments of the call are passed to :meth:`!__new__` and, in the typical case, to :meth:`~object.__init__` to initialize the new instance.
To create a module dynamically rather than using the import system, it's recommended to use :func:`importlib.util.module_from_spec`, which will set the various import-controlled attributes to appropriate values. It's also possible to use the :class:`types.ModuleType` constructor to create modules directly, but this technique is more error-prone, as most attributes must be manually set on the module object after it has been created when using this approach.
This attribute is used instead of :attr:`~module.__name__` to calculate explicit relative imports for main modules. It defaults to ``None`` for modules created dynamically using the :class:`types.ModuleType` constructor; use :func:`importlib.util.module_from_spec` instead to ensure the attribute is set to a :class:`str`.
This attribute now defaults to ``None`` for modules created dynamically using the :class:`types.ModuleType` constructor. Previously the attribute was optional.
:attr:`!__loader__` defaults to ``None`` for modules created dynamically using the :class:`types.ModuleType` constructor; use :func:`importlib.util.module_from_spec` instead to ensure the attribute is set to a :term:`loader` object.
An optional attribute, :attr:`!__file__` indicates the pathname of the file from which the module was loaded (if loaded from a file), or the pathname of the shared library file for extension modules loaded dynamically from a shared library. It might be missing for certain types of modules, such as C modules that are statically linked into the interpreter, and the :ref:`import system <importsystem>` may opt to leave it unset if it has no semantic meaning (for example, a module loaded from a database).
Custom class types are typically created by class definitions (see section :ref:`class`). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., ``C.x`` is translated to ``C.__dict__["x"]`` (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of 'diamond' inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found at :ref:`python_2.3_mro`.
A :class:`mapping proxy <types.MappingProxyType>` providing a read-only view of the class's namespace. See also: :attr:`__dict__ attributes <object.__dict__>`.
The single base class in the inheritance chain that is responsible for the memory layout of instances. This attribute corresponds to :c:member:`~PyTypeObject.tp_base` at the C level.
A :class:`tuple` containing the :ref:`type parameters <type-params>` of a :ref:`generic class <generic-classes>`.
The line number of the first line of the class definition, including decorators. Setting the :attr:`~type.__module__` attribute removes the :attr:`!__firstlineno__` item from the type's dictionary.
This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in :attr:`~type.__mro__`.
Internal types
A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.
Traceback objects represent the stack trace of an :ref:`exception <tut-errors>`. A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling :class:`types.TracebackType`.
The :func:`slice` type now supports :ref:`subscription <subscriptions>`. For example, ``slice[float]`` may be used in type annotations to indicate a slice containing :type:`float` objects.
Special read-only attributes: :attr:`~slice.start` is the lower bound; :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step value; each is ``None`` if omitted. These attributes can have any type.
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python's approach to :dfn:`operator overloading`, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named :meth:`~object.__getitem__`, and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x, i)``. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically :exc:`AttributeError` or :exc:`TypeError`).
Setting a special method to ``None`` indicates that the corresponding operation is not available. For example, if a class sets :meth:`~object.__iter__` to ``None``, the class is not iterable, so calling :func:`iter` on its instances will raise a :exc:`TypeError` (without falling back to :meth:`~object.__getitem__`). [#]_
When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the :ref:`NodeList <dom-nodelist-objects>` interface in the W3C's Document Object Model.)
:meth:`__new__` is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.
Because :meth:`__new__` and :meth:`__init__` work together in constructing objects (:meth:`__new__` to create it, and :meth:`__init__` to customize it), no non-``None`` value may be returned by :meth:`__init__`; doing so will cause a :exc:`TypeError` to be raised at runtime.
The default implementation defined by the built-in type :class:`object` calls :meth:`object.__repr__`.
Called by the :func:`format` built-in function, and by extension, evaluation of :ref:`formatted string literals <f-strings>` and the :meth:`str.format` method, to produce a "formatted" string representation of an object. The *format_spec* argument is a string that contains a description of the formatting options desired. The interpretation of the *format_spec* argument is up to the type implementing :meth:`__format__`, however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.
The __format__ method of ``object`` itself raises a :exc:`TypeError` if passed any non-empty string.
By default, the :class:`object` class provides implementations consistent with :ref:`expressions-value-comparisons`: equality compares according to object identity, and order comparisons raise :exc:`TypeError`. Each default method may generate these results directly, but may also return :data:`NotImplemented`.
There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection, :meth:`__le__` and :meth:`__ge__` are each other's reflection, and :meth:`__eq__` and :meth:`__ne__` are their own reflection. If the operands are of different types, and the right operand's type is a direct or indirect subclass of the left operand's type, the reflected method of the right operand has priority, otherwise the left operand's method has priority. Virtual subclassing is not considered.
:func:`hash` truncates the value returned from an object's custom :meth:`__hash__` method to the size of a :c:type:`Py_ssize_t`. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an object's :meth:`__hash__` must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. An easy way to do this is with ``python -c "import sys; print(sys.hash_info.width)"``.
A class that overrides :meth:`__eq__` and does not define :meth:`__hash__` will have its :meth:`__hash__` implicitly set to ``None``. When the :meth:`__hash__` method of a class is ``None``, instances of the class will raise an appropriate :exc:`TypeError` when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking ``isinstance(obj, collections.abc.Hashable)``.
If a class that does not override :meth:`__eq__` wishes to suppress hash support, it should include ``__hash__ = None`` in the class definition. A class which defines its own :meth:`__hash__` that explicitly raises a :exc:`TypeError` would be incorrectly identified as hashable by an ``isinstance(obj, collections.abc.Hashable)`` call.
For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the ``__class__`` attribute of a module object to a subclass of :class:`types.ModuleType`. For example::
import sys from types import ModuleType class VerboseModule(ModuleType): def __repr__(self): return f'Verbose {self.__name__}' def __setattr__(self, attr, value): print(f'Setting {attr}...') super().__setattr__(attr, value) sys.modules[__name__].__class__ = VerboseModule
The attribute :attr:`!__objclass__` is interpreted by the :mod:`inspect` module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).
The default behavior for attribute access is to get, set, or delete the attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and continuing through the base classes of ``type(a)`` excluding metaclasses.
If binding to an object instance, ``a.x`` is transformed into the call: ``type(a).__dict__['x'].__get__(a, type(a))``.
:exc:`TypeError` will be raised if *__slots__* other than *__dict__* and *__weakref__* are defined for a class derived from a :c:member:`"variable-length" built-in type <PyTypeObject.tp_itemsize>` such as :class:`int`, :class:`bytes`, and :class:`type`, except :class:`tuple`.
:ref:`Multiple inheritance <multiple-inheritance>` with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise :exc:`TypeError`.
The metaclass hint ``metaclass`` is consumed by the rest of the type machinery, and is never passed to ``__init_subclass__`` implementations. The actual metaclass (rather than the explicit hint) can be accessed as ``type(cls)``.
When a class is created, :meth:`!type.__new__` scans the class variables and makes callbacks to those with a :meth:`~object.__set_name__` hook.
By default, classes are constructed using :func:`type`. The class body is executed in a new namespace and the class name is bound locally to the result of ``type(name, bases, namespace)``.
class Meta(type): pass class MyClass(metaclass=Meta): pass class MySubclass(MyClass): pass
If a base that appears in a class definition is not an instance of :class:`type`, then an :meth:`!__mro_entries__` method is searched on the base. If an :meth:`!__mro_entries__` method is found, the base is substituted with the result of a call to :meth:`!__mro_entries__` when creating the class. The method is called with the original bases tuple passed to the *bases* parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.
:func:`types.resolve_bases`
Dynamically resolve bases that are not instances of :class:`type`.
:func:`types.get_original_bases`
Core support for typing module and generic types.
if no bases and no explicit metaclass are given, then :func:`type` is used;
if an explicit metaclass is given and it is *not* an instance of :func:`type`, then it is used directly as the metaclass;
if an instance of :func:`type` is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used.
The most derived metaclass is selected from the explicitly specified metaclass (if any) and the metaclasses (i.e. ``type(cls)``) of all specified base classes. The most derived metaclass is one which is a subtype of *all* of these candidate metaclasses. If none of the candidate metaclasses meets that criterion, then the class definition will fail with ``TypeError``.
In CPython 3.6 and later, the ``__class__`` cell is passed to the metaclass as a ``__classcell__`` entry in the class namespace. If present, this must be propagated up to the ``type.__new__`` call in order for the class to be initialised correctly. Failing to do so will result in a :exc:`RuntimeError` in Python 3.8.
When using the default metaclass :class:`type`, or any metaclass that ultimately calls ``type.__new__``, the following additional customization steps are invoked after creating the class object:
The ``type.__new__`` method collects all of the attributes in the class namespace that define a :meth:`~object.__set_name__` method;
When a new class is created by ``type.__new__``, the object provided as the namespace parameter is copied to a new ordered mapping and the original object is discarded. The new copy is wrapped in a read-only proxy, which becomes the :attr:`~type.__dict__` attribute of the class object.
In particular, the metaclass :class:`abc.ABCMeta` implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as "virtual base classes" to any class or type (including built-in types), including other ABCs.
Note that these methods are looked up on the type (metaclass) of a class. They cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class.
Includes the specification for customizing :func:`isinstance` and :func:`issubclass` behavior through :meth:`~type.__instancecheck__` and :meth:`~type.__subclasscheck__`, with motivation for this functionality in the context of adding Abstract Base Classes (see the :mod:`abc` module) to the language.
Emulating generic types
When using :term:`type annotations<annotation>`, it is often useful to *parameterize* a :term:`generic type` using Python's square-brackets notation. For example, the annotation ``list[int]`` might be used to signify a :class:`list` in which all the elements are of type :class:`int`.
:pep:`484` - Type Hints
Introducing Python's framework for type annotations
:ref:`Generic Alias Types<types-genericalias>`
Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.
Return an object representing the specialization of a generic class by type arguments found in *key*.
The purpose of :meth:`~object.__class_getitem__` is to allow runtime parameterization of standard-library generic classes in order to more easily apply :term:`type hints<type hint>` to these classes.
To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements :meth:`~object.__class_getitem__`, or inherit from :class:`typing.Generic`, which has its own implementation of ``__class_getitem__()``.
Custom implementations of :meth:`~object.__class_getitem__` on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. Using ``__class_getitem__()`` on any class for purposes other than type hinting is discouraged.
Usually, the :ref:`subscription<subscriptions>` of an object using square brackets will call the :meth:`~object.__getitem__` instance method defined on the object's class. However, if the object being subscribed is itself a class, the class method :meth:`~object.__class_getitem__` may be called instead. ``__class_getitem__()`` should return a :ref:`GenericAlias<types-genericalias>` object if it is properly defined.
from inspect import isclass def subscribe(obj, x): """Return the result of the expression 'obj[x]'""" class_of_obj = type(obj) # If the class of obj defines __getitem__, # call class_of_obj.__getitem__(obj, x) if hasattr(class_of_obj, '__getitem__'): return class_of_obj.__getitem__(obj, x) # Else, if obj is a class and defines __class_getitem__, # call obj.__class_getitem__(x) elif isclass(obj) and hasattr(obj, '__class_getitem__'): return obj.__class_getitem__(x) # Else, raise an exception else: raise TypeError( f"'{class_of_obj.__name__}' object is not subscriptable" )
In Python, all classes are themselves instances of other classes. The class of a class is known as that class's :term:`metaclass`, and most classes have the :class:`type` class as their metaclass. :class:`type` does not define :meth:`~object.__getitem__`, meaning that expressions such as ``list[int]``, ``dict[str, float]`` and ``tuple[str, bytes]`` all result in :meth:`~object.__class_getitem__` being called::
>>> # list has class "type" as its metaclass, like most classes: >>> type(list) <class 'type'> >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes) True >>> # "list[int]" calls "list.__class_getitem__(int)" >>> list[int] list[int] >>> # list.__class_getitem__ returns a GenericAlias object: >>> type(list[int]) <class 'types.GenericAlias'>
>>> from enum import Enum >>> class Menu(Enum): ... """A breakfast menu""" ... SPAM = 'spam' ... BACON = 'bacon' ... >>> # Enum classes have a custom metaclass: >>> type(Menu) <class 'enum.EnumMeta'> >>> # EnumMeta defines __getitem__, >>> # so __class_getitem__ is not called, >>> # and the result is not a GenericAlias object: >>> Menu['SPAM'] <Menu.SPAM: 'spam'> >>> type(Menu['SPAM']) <enum 'Menu'>
:pep:`560` - Core Support for typing module and generic types
Called when the instance is "called" as a function; if this method is defined, ``x(arg1, arg2, ...)`` roughly translates to ``type(x).__call__(x, arg1, ...)``. The :class:`object` class itself does not provide this method.
Emulating container types
Mutable sequences should provide methods :meth:`~sequence.append`, :meth:`~sequence.clear`, :meth:`~sequence.count`, :meth:`~sequence.extend`, :meth:`~sequence.index`, :meth:`~sequence.insert`, :meth:`~sequence.pop`, :meth:`~sequence.remove`, and :meth:`~sequence.reverse`, like Python standard :class:`list` objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods :meth:`~object.__add__`, :meth:`~object.__radd__`, :meth:`~object.__iadd__`, :meth:`~object.__mul__`, :meth:`~object.__rmul__` and :meth:`~object.__imul__` described below; they should not define other numerical operators.
There are two types of built-in objects that support subscription via :meth:`!__getitem__`:
If *subscript* is of an inappropriate type, :meth:`!__getitem__` should raise :exc:`TypeError`. If *subscript* has an inappropriate value, :meth:`!__getitem__` should raise an :exc:`LookupError` or one of its subclasses (:exc:`IndexError` for sequences; :exc:`KeyError` for mappings).
Emulating numeric types
These methods are called to implement the binary arithmetic operations (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``). For instance, to evaluate the expression ``x + y``, where *x* is an instance of a class that has an :meth:`__add__` method, ``type(x).__add__(x, y)`` is called. The :meth:`__divmod__` method should be the equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be related to :meth:`__truediv__`. Note that :meth:`__pow__` should be defined to accept an optional third argument if the three-argument version of the built-in :func:`pow` function is to be supported.
These methods are called to implement the binary arithmetic operations (``+``, ``-``, ``*``, ``@``, ``/``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``, ``&``, ``^``, ``|``) with reflected (swapped) operands. These functions are only called if the operands are of different types, when the left operand does not support the corresponding operation [#]_, or the right operand's class is derived from the left operand's class. [#]_ For instance, to evaluate the expression ``x - y``, where *y* is an instance of a class that has an :meth:`__rsub__` method, ``type(y).__rsub__(y, x)`` is called if ``type(x).__sub__(x, y)`` returns :data:`NotImplemented` or ``type(y)`` is a subclass of ``type(x)``. [#]_
If the right operand's type is a subclass of the left operand's type and that subclass provides a different implementation of the reflected method for the operation, this method will be called before the left operand's non-reflected method. This behavior allows subclasses to override their ancestors' operations.
Called to implement the built-in functions :func:`complex`, :func:`int` and :func:`float`. Should return a value of the appropriate type.
Called to implement :func:`operator.index`, and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in :func:`bin`, :func:`hex` and :func:`oct` functions). Presence of this method indicates that the numeric object is an integer type. Must return an integer.
For more information on context managers, see :ref:`typecontextmanager`. The :class:`object` class itself does not provide the context manager methods.
For example, if ``MyClass.__match_args__`` is ``("left", "center", "right")`` that means that ``case MyClass(x, y)`` is equivalent to ``case MyClass(left=x, center=y)``. Note that the number of arguments in the pattern must be smaller than or equal to the number of elements in *__match_args__*; if it is larger, the pattern match attempt will raise a :exc:`TypeError`.
Emulating buffer types
The :ref:`buffer protocol <bufferobjects>` provides a way for Python objects to expose efficient access to a low-level memory array. This protocol is implemented by builtin types such as :class:`bytes` and :class:`memoryview`, and third-party libraries may define additional buffer types.
While buffer types are usually implemented in C, it is also possible to implement the protocol in Python.
ABC for buffer types.
Functions, classes, and modules may contain :term:`annotations <annotation>`, which are a way to associate information (usually :term:`type hints <type hint>`) with a symbol.
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object's type, not in the object's instance dictionary. That behaviour is the reason why the following code raises an exception::
>>> class C: ... pass ... >>> c = C() >>> c.__len__ = lambda: 5 >>> len(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'C' has no len()
The rationale behind this behaviour lies with a number of special methods such as :meth:`~object.__hash__` and :meth:`~object.__repr__` that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself::
>>> 1 .__hash__() == hash(1) True >>> int.__hash__() == hash(int) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descriptor '__hash__' of 'int' object needs an argument
>>> type(1).__hash__(1) == hash(1) True >>> type(int).__hash__(int) == hash(int) True
>>> class Meta(type): ... def __getattribute__(*args): ... print("Metaclass getattribute invoked") ... return type.__getattribute__(*args) ... >>> class C(object, metaclass=Meta): ... def __len__(self): ... return 10 ... def __getattribute__(*args): ... print("Class getattribute invoked") ... return object.__getattribute__(*args) ... >>> c = C() >>> c.__len__() # Explicit lookup via instance Class getattribute invoked 10 >>> type(c).__len__(c) # Explicit lookup via type Metaclass getattribute invoked 10 >>> len(c) # Implicit lookup 10
The :term:`generator iterator` objects returned from generators decorated with :func:`types.coroutine` are also awaitable, but they do not implement :meth:`~object.__await__`.
The language doesn't place any restriction on the type or value of the objects yielded by the iterator returned by ``__await__``, as this is specific to the implementation of the asynchronous execution framework (e.g. :mod:`asyncio`) that will be managing the :term:`awaitable` object.
Coroutines are :ref:`generic <generics>` over the types of their yield, send, and return values, respectively.
The second signature \(type\[, value\[, traceback\]\]\) is deprecated and may be removed in a future version of Python.
Starting with Python 3.7, :meth:`~object.__aiter__` must return an asynchronous iterator object. Returning anything else will result in a :exc:`TypeError` error.
class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context')
It *is* possible in some cases to change an object's type, under certain controlled conditions. It generally isn't a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.
The :meth:`~object.__hash__`, :meth:`~object.__iter__`, :meth:`~object.__reversed__`, :meth:`~object.__contains__`, :meth:`~object.__class_getitem__` and :meth:`~os.PathLike.__fspath__` methods have special handling for this. Others will still raise a :exc:`TypeError`, but may do so by relying on the behavior that ``None`` is not callable.
For operands of the same type, it is assumed that if the non-reflected method (such as :meth:`~object.__add__`) fails then the operation is not supported, which is why the reflected method is not called.
If the right operand's type is a subclass of the left operand's type, the reflected method having precedence allows subclasses to override their ancestors' operations.
type
tipe
type of an object
set type
__type_params__ (function attribute)
__type_params__ (class attribute)
internal type
types, internal
immutable types