Teks sumber — English
Terjemahan — Bahasa Indonesia
:mod:`!typing` --- Support for type hints
:mod:`!typing` --- Dukungan untuk petunjuk tipe
**Source code:** :source:`Lib/typing.py`
**Kode sumber:** :source:`Lib/typing.py`
The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as :term:`type checkers <static type checker>`, IDEs, linters, etc.
Runtime Python tidak memberlakukan anotasi tipe fungsi dan variabel. Anotasi tersebut dapat digunakan oleh perkakas pihak ketiga seperti :term:`type checkers <static type checker>`, IDE, linter, dan sebagainya.
This module provides runtime support for type hints.
Modul ini menyediakan dukungan runtime untuk petunjuk tipe.
Consider the function below::
Perhatikan fungsi di bawah ini::
def surface_area_of_cube(edge_length: float) -> str:
return f"The surface area of the cube is {6 * edge_length ** 2}."
def surface_area_of_cube(edge_length: float) -> str:
return f"The surface area of the cube is {6 * edge_length ** 2}."
The function ``surface_area_of_cube`` takes an argument expected to be an instance of :class:`float`, as indicated by the :term:`type hint` ``edge_length: float``. The function is expected to return an instance of :class:`str`, as indicated by the ``-> str`` hint.
Fungsi ``surface_area_of_cube`` menerima sebuah argumen yang diharapkan berupa instance dari :class:`float`, sebagaimana ditunjukkan oleh :term:`type hint` ``edge_length: float``. Fungsi ini diharapkan mengembalikan sebuah instance dari :class:`str`, sebagaimana ditunjukkan oleh petunjuk ``-> str``.
While type hints can be simple classes like :class:`float` or :class:`str`, they can also be more complex. The :mod:`typing` module provides a vocabulary of more advanced type hints.
Meskipun petunjuk tipe dapat berupa kelas sederhana seperti :class:`float` atau :class:`str`, petunjuk tipe juga dapat lebih kompleks. Modul :mod:`typing` menyediakan kosakata petunjuk tipe yang lebih lanjut.
New features are frequently added to the ``typing`` module. The :pypi:`typing_extensions` package provides backports of these new features to older versions of Python.
Fitur-fitur baru sering ditambahkan ke modul ``typing``. Paket :pypi:`typing_extensions` menyediakan backport dari fitur-fitur baru ini untuk versi Python yang lebih lama.
`Typing cheat sheet <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_
`Typing cheat sheet <https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_
A quick overview of type hints (hosted at the mypy docs)
Gambaran singkat tentang petunjuk tipe (di-host di dokumen mypy)
Type System Reference section of `the mypy docs <https://mypy.readthedocs.io/en/stable/index.html>`_
Bagian Referensi Sistem Tipe dari `dokumen mypy <https://mypy.readthedocs.io/en/stable/index.html>`_
The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.)
Sistem tipe Python distandardisasi melalui PEP, sehingga referensi ini secara umum berlaku untuk sebagian besar pemeriksa tipe Python. (Beberapa bagian mungkin masih spesifik untuk mypy.)
`Static Typing with Python <https://typing.python.org/en/latest/>`_
`Static Typing with Python <https://typing.python.org/en/latest/>`_
Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.
Dokumentasi yang agnostik terhadap pemeriksa tipe, ditulis oleh komunitas, yang merinci fitur-fitur sistem tipe, perkakas terkait penipean yang berguna, dan praktik terbaik penipean.
Specification for the Python Type System
Spesifikasi untuk Sistem Tipe Python
The canonical, up-to-date specification of the Python type system can be found at `Specification for the Python type system <https://typing.python.org/en/latest/spec/index.html>`_.
Spesifikasi kanonis dan terbaru dari sistem tipe Python dapat ditemukan di `Spesifikasi untuk sistem tipe Python <https://typing.python.org/en/latest/spec/index.html>`_.
Type aliases
Alias Tipe
A type alias is defined using the :keyword:`type` statement, which creates an instance of :class:`TypeAliasType`. In this example, ``Vector`` and ``list[float]`` will be treated equivalently by static type checkers::
Alias tipe didefinisikan menggunakan pernyataan :keyword:`type`, yang membuat sebuah instance dari :class:`TypeAliasType`. Dalam contoh ini, ``Vector`` dan ``list[float]`` akan diperlakukan setara oleh pemeriksa tipe statis::
type Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
type Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
Type aliases are useful for simplifying complex type signatures. For example::
Alias tipe berguna untuk menyederhanakan signatur tipe yang kompleks. Sebagai contoh::
from collections.abc import Sequence
type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
) -> None:
...
from collections.abc import Sequence
type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
) -> None:
...
The :keyword:`type` statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment::
Pernyataan :keyword:`type` baru ada di Python 3.12. Untuk kompatibilitas mundur, alias tipe juga dapat dibuat melalui penugasan sederhana::
Vector = list[float]
Vector = list[float]
Or marked with :data:`TypeAlias` to make it explicit that this is a type alias, not a normal variable assignment::
Atau ditandai dengan :data:`TypeAlias` untuk menegaskan bahwa ini adalah alias tipe, bukan penugasan variabel biasa::
from typing import TypeAlias
Vector: TypeAlias = list[float]
from typing import TypeAlias
Vector: TypeAlias = list[float]
NewType
NewType
Use the :class:`NewType` helper to create distinct types::
Gunakan pembantu :class:`NewType` untuk membuat tipe yang berbeda::
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
from typing import NewType
UserId = NewType('UserId', int)
some_id = UserId(524313)
The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors::
Pemeriksa tipe statis akan memperlakukan tipe baru seolah-olah tipe tersebut adalah subkelas dari tipe aslinya. Hal ini berguna untuk membantu menemukan kesalahan logika::
def get_user_name(user_id: UserId) -> str:
...
# passes type checking
user_a = get_user_name(UserId(42351))
# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
def get_user_name(user_id: UserId) -> str:
...
# passes type checking
user_a = get_user_name(UserId(42351))
# fails type checking; an int is not a UserId
user_b = get_user_name(-1)
You may still perform all ``int`` operations on a variable of type ``UserId``, but the result will always be of type ``int``. This lets you pass in a ``UserId`` wherever an ``int`` might be expected, but will prevent you from accidentally creating a ``UserId`` in an invalid way::
Anda masih dapat melakukan semua operasi ``int`` pada sebuah variabel bertipe ``UserId``, tetapi hasilnya akan selalu bertipe ``int``. Hal ini memungkinkan Anda meneruskan ``UserId`` ke mana pun ``int`` diharapkan, tetapi akan mencegah Anda membuat ``UserId`` secara tidak sengaja dengan cara yang tidak valid::
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)
Note that these checks are enforced only by the static type checker. At runtime, the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a callable that immediately returns whatever parameter you pass it. That means the expression ``Derived(some_value)`` does not create a new class or introduce much overhead beyond that of a regular function call.
Perlu diperhatikan bahwa pemeriksaan ini hanya diberlakukan oleh pemeriksa tipe statis. Pada saat runtime, pernyataan ``Derived = NewType('Derived', Base)`` akan membuat ``Derived`` menjadi sebuah callable yang langsung mengembalikan apa pun parameter yang Anda teruskan. Artinya, ekspresi ``Derived(some_value)`` tidak membuat sebuah kelas baru atau menimbulkan banyak overhead di luar pemanggilan fungsi biasa.
More precisely, the expression ``some_value is Derived(some_value)`` is always true at runtime.
Lebih tepatnya, ekspresi ``some_value is Derived(some_value)`` selalu bernilai benar pada saat runtime.
It is invalid to create a subtype of ``Derived``::
Membuat subtipe dari ``Derived`` tidak valid::
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
from typing import NewType
UserId = NewType('UserId', int)
# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass
However, it is possible to create a :class:`NewType` based on a 'derived' ``NewType``::
Namun, dimungkinkan untuk membuat sebuah :class:`NewType` berdasarkan ``NewType`` yang 'diturunkan'::
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
from typing import NewType
UserId = NewType('UserId', int)
ProUserId = NewType('ProUserId', UserId)
and typechecking for ``ProUserId`` will work as expected.
dan pemeriksaan tipe untuk ``ProUserId`` akan bekerja sebagaimana mestinya.
See :pep:`484` for more details.
Lihat :pep:`484` untuk detail selengkapnya.
Recall that the use of a type alias declares two types to be *equivalent* to one another. Doing ``type Alias = Original`` will make the static type checker treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases. This is useful when you want to simplify complex type signatures.
Ingatlah bahwa penggunaan alias tipe menyatakan dua tipe *setara* satu sama lain. Melakukan ``type Alias = Original`` akan membuat pemeriksa tipe statis memperlakukan ``Alias`` sebagai *persis setara* dengan ``Original`` dalam semua kasus. Hal ini berguna ketika Anda ingin menyederhanakan signatur tipe yang kompleks.
In contrast, ``NewType`` declares one type to be a *subtype* of another. Doing ``Derived = NewType('Derived', Original)`` will make the static type checker treat ``Derived`` as a *subclass* of ``Original``, which means a value of type ``Original`` cannot be used in places where a value of type ``Derived`` is expected. This is useful when you want to prevent logic errors with minimal runtime cost.
Sebaliknya, ``NewType`` menyatakan satu tipe sebagai *subtipe* dari tipe lain. Melakukan ``Derived = NewType('Derived', Original)`` akan membuat pemeriksa tipe statis memperlakukan ``Derived`` sebagai *subkelas* dari ``Original``, yang berarti nilai bertipe ``Original`` tidak dapat digunakan di tempat yang mengharapkan nilai bertipe ``Derived``. Hal ini berguna ketika Anda ingin mencegah kesalahan logika dengan biaya runtime yang minimal.
``NewType`` is now a class rather than a function. As a result, there is some additional runtime cost when calling ``NewType`` over a regular function.
``NewType`` kini adalah sebuah kelas, bukan sebuah fungsi. Akibatnya, ada tambahan biaya runtime saat memanggil ``NewType`` dibandingkan dengan fungsi biasa.
The performance of calling ``NewType`` has been restored to its level in Python 3.9.
Kinerja pemanggilan ``NewType`` telah dipulihkan ke tingkatnya di Python 3.9.
Annotating callable objects
Menganotasi objek callable
Functions -- or other :term:`callable` objects -- can be annotated using :class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. ``Callable[[int], str]`` signifies a function that takes a single parameter of type :class:`int` and returns a :class:`str`.
Fungsi -- atau objek :term:`callable` lainnya -- dapat dianotasi menggunakan :class:`collections.abc.Callable` atau :data:`typing.Callable` yang sudah tidak disarankan lagi. ``Callable[[int], str]`` menandakan sebuah fungsi yang menerima satu parameter bertipe :class:`int` dan mengembalikan sebuah :class:`str`.
For example:
Sebagai contoh:
from collections.abc import Callable, Awaitable
def feeder(get_next_item: Callable[[], str]) -> None:
... # Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
... # Body
async def on_update(value: str) -> None:
... # Body
callback: Callable[[str], Awaitable[None]] = on_update
from collections.abc import Callable, Awaitable
def feeder(get_next_item: Callable[[], str]) -> None:
... # Body
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
... # Body
async def on_update(value: str) -> None:
... # Body
callback: Callable[[str], Awaitable[None]] = on_update
The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a :class:`ParamSpec`, :data:`Concatenate`, or an ellipsis (``...``). The return type must be a single type.
Sintaks subscription harus selalu digunakan dengan tepat dua nilai: daftar argumen dan tipe kembalian. Daftar argumen harus berupa daftar tipe, sebuah :class:`ParamSpec`, :data:`Concatenate`, atau elipsis (``...``). Tipe kembalian harus berupa satu tipe.
If a literal ellipsis ``...`` is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:
Jika elipsis literal ``...`` diberikan sebagai daftar argumen, hal itu menunjukkan bahwa callable dengan daftar parameter sembarang apa pun dapat diterima:
def concat(x: str, y: str) -> str:
return x + y
x: Callable[..., str]
x = str # OK
x = concat # Also OK
def concat(x: str, y: str) -> str:
return x + y
x: Callable[..., str]
x = str # OK
x = concat # Also OK
``Callable`` cannot express complex signatures such as functions that take a variadic number of arguments, :ref:`overloaded functions <overload>`, or functions that have keyword-only parameters. However, these signatures can be expressed by defining a :class:`Protocol` class with a :meth:`~object.__call__` method:
``Callable`` tidak dapat mengekspresikan signatur kompleks seperti fungsi yang menerima sejumlah argumen variadik, :ref:`fungsi yang di-overload <overload>`, atau fungsi yang memiliki parameter khusus kata kunci (keyword-only). Namun, signatur ini dapat diekspresikan dengan mendefinisikan sebuah kelas :class:`Protocol` dengan metode :meth:`~object.__call__`:
from collections.abc import Iterable
from typing import Protocol
class Combiner(Protocol):
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
for item in data:
...
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
...
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
...
batch_proc([], good_cb) # OK
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
# different name and kind in the callback
from collections.abc import Iterable
from typing import Protocol
class Combiner(Protocol):
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...
def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
for item in data:
...
def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
...
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
...
batch_proc([], good_cb) # OK
batch_proc([], bad_cb) # Error! Argument 2 has incompatible type because of
# different name and kind in the callback
Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using :class:`ParamSpec`. Additionally, if that callable adds or removes arguments from other callables, the :data:`Concatenate` operator may be used. They take the form ``Callable[ParamSpecVariable, ReturnType]`` and ``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]`` respectively.
Callable yang menerima callable lain sebagai argumen dapat menunjukkan bahwa tipe parameternya saling bergantung satu sama lain menggunakan :class:`ParamSpec`. Selain itu, jika callable tersebut menambah atau menghapus argumen dari callable lain, operator :data:`Concatenate` dapat digunakan. Bentuknya adalah ``Callable[ParamSpecVariable, ReturnType]`` dan ``Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType]``.
``Callable`` now supports :class:`ParamSpec` and :data:`Concatenate`. See :pep:`612` for more details.
``Callable`` kini mendukung :class:`ParamSpec` dan :data:`Concatenate`. Lihat :pep:`612` untuk detail selengkapnya.
The documentation for :class:`ParamSpec` and :class:`Concatenate` provides examples of usage in ``Callable``.
Dokumentasi untuk :class:`ParamSpec` dan :class:`Concatenate` memberikan contoh penggunaan dalam ``Callable``.
Generics
Generik
Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.
Karena informasi tipe tentang objek yang disimpan dalam container tidak dapat disimpulkan secara statis dengan cara yang generik, banyak kelas container di pustaka standar mendukung subscription untuk menunjukkan tipe yang diharapkan dari elemen-elemen container.
from collections.abc import Mapping, Sequence
class Employee: ...
# Sequence[Employee] indicates that all elements in the sequence
# must be instances of "Employee".
# Mapping[str, str] indicates that all keys and all values in the mapping
# must be strings.
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
from collections.abc import Mapping, Sequence
class Employee: ...
# Sequence[Employee] indicates that all elements in the sequence
# must be instances of "Employee".
# Mapping[str, str] indicates that all keys and all values in the mapping
# must be strings.
def notify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) -> None: ...
Generic functions and classes can be parameterized by using :ref:`type parameter syntax <type-params>`::
Fungsi dan kelas generik dapat diparameterisasi dengan menggunakan :ref:`sintaks parameter tipe <type-params>`::
from collections.abc import Sequence
def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar "T"
return l[0]
from collections.abc import Sequence
def first[T](l: Sequence[T]) -> T: # Function is generic over the TypeVar "T"
return l[0]
Or by using the :class:`TypeVar` factory directly::
Atau dengan menggunakan factory :class:`TypeVar` secara langsung::
from collections.abc import Sequence
from typing import TypeVar
U = TypeVar('U') # Declare type variable "U"
def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar "U"
return l[1]
from collections.abc import Sequence
from typing import TypeVar
U = TypeVar('U') # Declare type variable "U"
def second(l: Sequence[U]) -> U: # Function is generic over the TypeVar "U"
return l[1]
Syntactic support for generics is new in Python 3.12.
Dukungan sintaksis untuk generik baru ada di Python 3.12.
Annotating tuples
Menganotasi tuple
For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example::
Untuk sebagian besar container di Python, sistem tipe mengasumsikan bahwa semua elemen dalam container akan bertipe sama. Sebagai contoh::
from collections.abc import Mapping
# Type checker will infer that all elements in ``x`` are meant to be ints
x: list[int] = []
# Type checker error: ``list`` only accepts a single type argument:
y: list[int, str] = [1, 'foo']
# Type checker will infer that all keys in ``z`` are meant to be strings,
# and that all values in ``z`` are meant to be either strings or ints
z: Mapping[str, str | int] = {}
from collections.abc import Mapping
# Type checker will infer that all elements in ``x`` are meant to be ints
x: list[int] = []
# Type checker error: ``list`` only accepts a single type argument:
y: list[int, str] = [1, 'foo']
# Type checker will infer that all keys in ``z`` are meant to be strings,
# and that all values in ``z`` are meant to be either strings or ints
z: Mapping[str, str | int] = {}
:class:`list` only accepts one type argument, so a type checker would emit an error on the ``y`` assignment above. Similarly, :class:`~collections.abc.Mapping` only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.
:class:`list` hanya menerima satu argumen tipe, sehingga pemeriksa tipe akan memunculkan galat pada penugasan ``y`` di atas. Demikian pula, :class:`~collections.abc.Mapping` hanya menerima dua argumen tipe: yang pertama menunjukkan tipe kunci, dan yang kedua menunjukkan tipe nilai.
Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python's typing system. :class:`tuple` accepts *any number* of type arguments::
Namun, tidak seperti kebanyakan container Python lainnya, dalam kode Python yang idiomatis, tuple umumnya memiliki elemen yang tidak semuanya bertipe sama. Karena alasan ini, tuple diperlakukan secara khusus dalam sistem tipe Python. :class:`tuple` menerima *sejumlah* argumen tipe::
# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int
x: tuple[int] = (5,)
# OK: ``y`` is assigned to a tuple of length 2;
# element 1 is an int, element 2 is a str
y: tuple[int, str] = (5, "foo")
# Error: the type annotation indicates a tuple of length 1,
# but ``z`` has been assigned to a tuple of length 3
z: tuple[int] = (1, 2, 3)
# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int
x: tuple[int] = (5,)
# OK: ``y`` is assigned to a tuple of length 2;
# element 1 is an int, element 2 is a str
y: tuple[int, str] = (5, "foo")
# Error: the type annotation indicates a tuple of length 1,
# but ``z`` has been assigned to a tuple of length 3
z: tuple[int] = (1, 2, 3)
To denote a tuple which could be of *any* length, and in which all elements are of the same type ``T``, use the literal ellipsis ``...``: ``tuple[T, ...]``. To denote an empty tuple, use ``tuple[()]``. Using plain ``tuple`` as an annotation is equivalent to using ``tuple[Any, ...]``::
Untuk menunjukkan tuple yang dapat memiliki panjang *berapa pun*, dan semua elemennya bertipe sama ``T``, gunakan elipsis literal ``...``: ``tuple[T, ...]``. Untuk menunjukkan tuple kosong, gunakan ``tuple[()]``. Menggunakan ``tuple`` biasa sebagai anotasi setara dengan menggunakan ``tuple[Any, ...]``::
x: tuple[int, ...] = (1, 2)
# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length
x = (1, 2, 3)
x = ()
# This reassignment is an error: all elements in ``x`` must be ints
x = ("foo", "bar")
# ``y`` can only ever be assigned to an empty tuple
y: tuple[()] = ()
z: tuple = ("foo", "bar")
# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``
z = (1, 2, 3)
z = ()
x: tuple[int, ...] = (1, 2)
# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length
x = (1, 2, 3)
x = ()
# This reassignment is an error: all elements in ``x`` must be ints
x = ("foo", "bar")
# ``y`` can only ever be assigned to an empty tuple
y: tuple[()] = ()
z: tuple = ("foo", "bar")
# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``
z = (1, 2, 3)
z = ()
The type of class objects
Tipe objek kelas
A variable annotated with ``C`` may accept a value of type ``C``. In contrast, a variable annotated with ``type[C]`` (or deprecated :class:`typing.Type[C] <Type>`) may accept values that are classes themselves -- specifically, it will accept the *class object* of ``C``. For example::
Sebuah variabel yang dianotasi dengan ``C`` dapat menerima nilai bertipe ``C``. Sebaliknya, sebuah variabel yang dianotasi dengan ``type[C]`` (atau :class:`typing.Type[C] <Type>` yang sudah tidak disarankan lagi) dapat menerima nilai yang berupa kelas itu sendiri -- secara spesifik, variabel tersebut akan menerima *objek kelas* dari ``C``. Sebagai contoh::
a = 3 # Has type ``int``
b = int # Has type ``type[int]``
c = type(a) # Also has type ``type[int]``
a = 3 # Has type ``int``
b = int # Has type ``type[int]``
c = type(a) # Also has type ``type[int]``
Note that ``type[C]`` is covariant::
Perlu diperhatikan bahwa ``type[C]`` bersifat kovarian::
class User: ...
class ProUser(User): ...
class TeamUser(User): ...
def make_new_user(user_class: type[User]) -> User:
# ...
return user_class()
make_new_user(User) # OK
make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
make_new_user(TeamUser) # Still fine
make_new_user(User()) # Error: expected ``type[User]`` but got ``User``
make_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]``
class User: ...
class ProUser(User): ...
class TeamUser(User): ...
def make_new_user(user_class: type[User]) -> User:
# ...
return user_class()
make_new_user(User) # OK
make_new_user(ProUser) # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
make_new_user(TeamUser) # Still fine
make_new_user(User()) # Error: expected ``type[User]`` but got ``User``
make_new_user(int) # Error: ``type[int]`` is not a subtype of ``type[User]``
The only legal parameters for :class:`type` are classes, :data:`Any`, :ref:`type variables <generics>`, and unions of any of these types. For example::
Satu-satunya parameter yang sah untuk :class:`type` adalah kelas, :data:`Any`, :ref:`variabel tipe <generics>`, dan gabungan (union) dari tipe-tipe tersebut. Sebagai contoh::
def new_non_team_user(user_class: type[BasicUser | ProUser]): ...
new_non_team_user(BasicUser) # OK
new_non_team_user(ProUser) # OK
new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype
# of ``type[BasicUser | ProUser]``
new_non_team_user(User) # Also an error
def new_non_team_user(user_class: type[BasicUser | ProUser]): ...
new_non_team_user(BasicUser) # OK
new_non_team_user(ProUser) # OK
new_non_team_user(TeamUser) # Error: ``type[TeamUser]`` is not a subtype
# of ``type[BasicUser | ProUser]``
new_non_team_user(User) # Also an error
``type[Any]`` is equivalent to :class:`type`, which is the root of Python's :ref:`metaclass hierarchy <metaclasses>`.
``type[Any]`` setara dengan :class:`type`, yang merupakan akar dari :ref:`hierarki metaclass <metaclasses>` Python.
Annotating generators and coroutines
Menganotasi generator dan coroutine
A generator can be annotated using the generic type :class:`Generator[YieldType, SendType, ReturnType] <collections.abc.Generator>`. For example::
Sebuah generator dapat dianotasi menggunakan tipe generik :class:`Generator[YieldType, SendType, ReturnType] <collections.abc.Generator>`. Sebagai contoh::
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
Note that unlike many other generic classes in the standard library, the ``SendType`` of :class:`~collections.abc.Generator` behaves contravariantly, not covariantly or invariantly.
Perlu diperhatikan bahwa tidak seperti banyak kelas generik lainnya di pustaka standar, ``SendType`` dari :class:`~collections.abc.Generator` berperilaku kontravarian, bukan kovarian atau invarian.
The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`::
Parameter ``SendType`` dan ``ReturnType`` secara default bernilai :const:`!None`::
def infinite_stream(start: int) -> Generator[int]:
while True:
yield start
start += 1
def infinite_stream(start: int) -> Generator[int]:
while True:
yield start
start += 1
It is also possible to set these types explicitly::
Dimungkinkan juga untuk menetapkan tipe-tipe ini secara eksplisit::
def infinite_stream(start: int) -> Generator[int, None, None]:
while True:
yield start
start += 1
def infinite_stream(start: int) -> Generator[int, None, None]:
while True:
yield start
start += 1
Simple generators that only ever yield values can also be annotated as having a return type of either :class:`Iterable[YieldType] <collections.abc.Iterable>` or :class:`Iterator[YieldType] <collections.abc.Iterator>`::
Generator sederhana yang hanya menghasilkan nilai (yield) juga dapat dianotasi dengan tipe kembalian :class:`Iterable[YieldType] <collections.abc.Iterable>` atau :class:`Iterator[YieldType] <collections.abc.Iterator>`::
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
def infinite_stream(start: int) -> Iterator[int]:
while True:
yield start
start += 1
Async generators are handled in a similar fashion, but don't expect a ``ReturnType`` type argument (:class:`AsyncGenerator[YieldType, SendType] <collections.abc.AsyncGenerator>`). The ``SendType`` argument defaults to :const:`!None`, so the following definitions are equivalent::
Generator async ditangani dengan cara yang serupa, tetapi tidak mengharapkan argumen tipe ``ReturnType`` (:class:`AsyncGenerator[YieldType, SendType] <collections.abc.AsyncGenerator>`). Argumen ``SendType`` secara default bernilai :const:`!None`, sehingga definisi-definisi berikut setara::
async def infinite_stream(start: int) -> AsyncGenerator[int]:
while True:
yield start
start = await increment(start)
async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
while True:
yield start
start = await increment(start)
async def infinite_stream(start: int) -> AsyncGenerator[int]:
while True:
yield start
start = await increment(start)
async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
while True:
yield start
start = await increment(start)
As in the synchronous case, :class:`AsyncIterable[YieldType] <collections.abc.AsyncIterable>` and :class:`AsyncIterator[YieldType] <collections.abc.AsyncIterator>` are available as well::
Seperti dalam kasus sinkron, :class:`AsyncIterable[YieldType] <collections.abc.AsyncIterable>` dan :class:`AsyncIterator[YieldType] <collections.abc.AsyncIterator>` juga tersedia::
async def infinite_stream(start: int) -> AsyncIterator[int]:
while True:
yield start
start = await increment(start)
async def infinite_stream(start: int) -> AsyncIterator[int]:
while True:
yield start
start = await increment(start)
Coroutines can be annotated using :class:`Coroutine[YieldType, SendType, ReturnType] <collections.abc.Coroutine>`. Generic arguments correspond to those of :class:`~collections.abc.Generator`, for example::
Coroutine dapat dianotasi menggunakan :class:`Coroutine[YieldType, SendType, ReturnType] <collections.abc.Coroutine>`. Argumen generik sesuai dengan argumen :class:`~collections.abc.Generator`, misalnya::
from collections.abc import Coroutine
c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere
x = c.send('hi') # Inferred type of 'x' is list[str]
async def bar() -> None:
y = await c # Inferred type of 'y' is int
from collections.abc import Coroutine
c: Coroutine[list[str], str, int] # Some coroutine defined elsewhere
x = c.send('hi') # Inferred type of 'x' is list[str]
async def bar() -> None:
y = await c # Inferred type of 'y' is int
User-defined generic types
Tipe generik yang ditentukan pengguna
A user-defined class can be defined as a generic class.
Sebuah kelas yang ditentukan pengguna dapat didefinisikan sebagai kelas generik.
from logging import Logger
class LoggedVar[T]:
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
from logging import Logger
class LoggedVar[T]:
def __init__(self, value: T, name: str, logger: Logger) -> None:
self.name = name
self.logger = logger
self.value = value
def set(self, new: T) -> None:
self.log('Set ' + repr(self.value))
self.value = new
def get(self) -> T:
self.log('Get ' + repr(self.value))
return self.value
def log(self, message: str) -> None:
self.logger.info('%s: %s', self.name, message)
This syntax indicates that the class ``LoggedVar`` is parameterised around a single :ref:`type variable <typevar>` ``T`` . This also makes ``T`` valid as a type within the class body.
Sintaks ini menunjukkan bahwa kelas ``LoggedVar`` diparameterisasi berdasarkan satu :ref:`variabel tipe <typevar>` ``T``. Hal ini juga membuat ``T`` valid sebagai tipe di dalam badan kelas.
Generic classes implicitly inherit from :class:`Generic`. For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from :class:`Generic` to indicate a generic class::
Kelas generik secara implisit mewarisi dari :class:`Generic`. Untuk kompatibilitas dengan Python 3.11 dan yang lebih lama, dimungkinkan juga untuk mewarisi secara eksplisit dari :class:`Generic` untuk menunjukkan sebuah kelas generik::
from typing import TypeVar, Generic
T = TypeVar('T')
class LoggedVar(Generic[T]):
...
from typing import TypeVar, Generic
T = TypeVar('T')
class LoggedVar(Generic[T]):
...
Generic classes have :meth:`~object.__class_getitem__` methods, meaning they can be parameterised at runtime (e.g. ``LoggedVar[int]`` below)::
Kelas generik memiliki metode :meth:`~object.__class_getitem__`, yang berarti kelas tersebut dapat diparameterisasi pada saat runtime (misalnya ``LoggedVar[int]`` di bawah)::
from collections.abc import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
from collections.abc import Iterable
def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
for var in vars:
var.set(0)
A generic type can have any number of type variables. All varieties of :class:`TypeVar` are permissible as parameters for a generic type::
Sebuah tipe generik dapat memiliki sejumlah variabel tipe. Semua jenis :class:`TypeVar` diizinkan sebagai parameter untuk sebuah tipe generik::
from typing import TypeVar, Generic, Sequence
class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
...
OldT = TypeVar('OldT', contravariant=True)
OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
OldS = TypeVar('OldS', int, str)
class OldWeirdTrio(Generic[OldT, OldB, OldS]):
...
from typing import TypeVar, Generic, Sequence
class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
...
OldT = TypeVar('OldT', contravariant=True)
OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
OldS = TypeVar('OldS', int, str)
class OldWeirdTrio(Generic[OldT, OldB, OldS]):
...
Each type variable argument to :class:`Generic` must be distinct. This is thus invalid::
Setiap argumen variabel tipe untuk :class:`Generic` harus berbeda. Jadi, berikut ini tidak valid::
from typing import TypeVar, Generic
...
class Pair[M, M]: # SyntaxError
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
from typing import TypeVar, Generic
...
class Pair[M, M]: # SyntaxError
...
T = TypeVar('T')
class Pair(Generic[T, T]): # INVALID
...
Generic classes can also inherit from other classes::
Kelas generik juga dapat mewarisi dari kelas lain::
from collections.abc import Sized
class LinkedList[T](Sized):
...
from collections.abc import Sized
class LinkedList[T](Sized):
...
When inheriting from generic classes, some type parameters could be fixed::
Saat mewarisi dari kelas generik, beberapa parameter tipe dapat ditetapkan::
from collections.abc import Mapping
class MyDict[T](Mapping[str, T]):
...
from collections.abc import Mapping
class MyDict[T](Mapping[str, T]):
...
In this case ``MyDict`` has a single parameter, ``T``.
Dalam hal ini ``MyDict`` memiliki satu parameter, ``T``.
Using a generic class without specifying type parameters assumes :data:`Any` for each position. In the following example, ``MyIterable`` is not generic but implicitly inherits from ``Iterable[Any]``:
Menggunakan sebuah kelas generik tanpa menentukan parameter tipe mengasumsikan :data:`Any` untuk setiap posisi. Dalam contoh berikut, ``MyIterable`` bukan generik tetapi secara implisit mewarisi dari ``Iterable[Any]``:
from collections.abc import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
...
from collections.abc import Iterable
class MyIterable(Iterable): # Same as Iterable[Any]
...
User-defined generic type aliases are also supported. Examples::
Alias tipe generik yang ditentukan pengguna juga didukung. Contoh::
from collections.abc import Iterable
type Response[S] = Iterable[S] | int
# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
...
type Vec[T] = Iterable[tuple[T, T]]
def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
return sum(x*y for x, y in v)
from collections.abc import Iterable
type Response[S] = Iterable[S] | int
# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
...
type Vec[T] = Iterable[tuple[T, T]]
def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
return sum(x*y for x, y in v)
For backward compatibility, generic type aliases can also be created through a simple assignment::
Untuk kompatibilitas mundur, alias tipe generik juga dapat dibuat melalui penugasan sederhana::
from collections.abc import Iterable
from typing import TypeVar
S = TypeVar("S")
Response = Iterable[S] | int
from collections.abc import Iterable
from typing import TypeVar
S = TypeVar("S")
Response = Iterable[S] | int
:class:`Generic` no longer has a custom metaclass.
:class:`Generic` tidak lagi memiliki metaclass kustom.
Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from :class:`Generic` or contain a type variable in one of their bases.
Dukungan sintaksis untuk generik dan alias tipe baru ada di versi 3.12. Sebelumnya, kelas generik harus secara eksplisit mewarisi dari :class:`Generic` atau mengandung sebuah variabel tipe di salah satu basisnya.
User-defined generics for parameter expressions are also supported via parameter specification variables in the form ``[**P]``. The behavior is consistent with type variables' described above as parameter specification variables are treated by the :mod:`!typing` module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a :class:`ParamSpec`::
Generik yang ditentukan pengguna untuk ekspresi parameter juga didukung melalui variabel spesifikasi parameter dalam bentuk ``[**P]``. Perilakunya konsisten dengan variabel tipe yang dijelaskan di atas, karena variabel spesifikasi parameter diperlakukan oleh modul :mod:`!typing` sebagai variabel tipe yang terspesialisasi. Satu-satunya pengecualian adalah bahwa daftar tipe dapat digunakan untuk menggantikan sebuah :class:`ParamSpec`::
>>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec
...
>>> Z[int, [dict, float]]
__main__.Z[int, [dict, float]]
>>> class Z[T, **P]: ... # T is a TypeVar; P is a ParamSpec
...
>>> Z[int, [dict, float]]
__main__.Z[int, [dict, float]]
Classes generic over a :class:`ParamSpec` can also be created using explicit inheritance from :class:`Generic`. In this case, ``**`` is not used::
Kelas yang generik terhadap sebuah :class:`ParamSpec` juga dapat dibuat menggunakan pewarisan eksplisit dari :class:`Generic`. Dalam hal ini, ``**`` tidak digunakan::
from typing import ParamSpec, Generic
P = ParamSpec('P')
class Z(Generic[P]):
...
from typing import ParamSpec, Generic
P = ParamSpec('P')
class Z(Generic[P]):
...
Another difference between :class:`TypeVar` and :class:`ParamSpec` is that a generic with only one parameter specification variable will accept parameter lists in the forms ``X[[Type1, Type2, ...]]`` and also ``X[Type1, Type2, ...]`` for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent::
Perbedaan lain antara :class:`TypeVar` dan :class:`ParamSpec` adalah bahwa sebuah generik yang hanya memiliki satu variabel spesifikasi parameter akan menerima daftar parameter dalam bentuk ``X[[Type1, Type2, ...]]`` dan juga ``X[Type1, Type2, ...]`` karena alasan estetika. Secara internal, bentuk terakhir dikonversi menjadi bentuk pertama, sehingga berikut ini setara::
>>> class X[**P]: ...
...
>>> X[int, str]
__main__.X[[int, str]]
>>> X[[int, str]]
__main__.X[[int, str]]
>>> class X[**P]: ...
...
>>> X[int, str]
__main__.X[[int, str]]
>>> X[[int, str]]
__main__.X[[int, str]]
Note that generics with :class:`ParamSpec` may not have correct ``__parameters__`` after substitution in some cases because they are intended primarily for static type checking.
Perlu diperhatikan bahwa generik dengan :class:`ParamSpec` mungkin tidak memiliki ``__parameters__`` yang benar setelah substitusi dalam beberapa kasus, karena generik tersebut terutama ditujukan untuk pemeriksaan tipe statis.
:class:`Generic` can now be parameterized over parameter expressions. See :class:`ParamSpec` and :pep:`612` for more details.
:class:`Generic` kini dapat diparameterisasi terhadap ekspresi parameter. Lihat :class:`ParamSpec` dan :pep:`612` untuk detail selengkapnya.
A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the :mod:`!typing` module are :term:`hashable` and comparable for equality.
Sebuah kelas generik yang ditentukan pengguna dapat memiliki ABC sebagai kelas dasar tanpa konflik metaclass. Metaclass generik tidak didukung. Hasil dari memparameterisasi generik di-cache, dan sebagian besar tipe dalam modul :mod:`!typing` bersifat :term:`hashable` dan dapat dibandingkan kesetaraannya.
The :data:`Any` type
Tipe :data:`Any`
A special kind of type is :data:`Any`. A static type checker will treat every type as assignable to :data:`Any` and :data:`Any` as assignable to every type.
Jenis tipe yang istimewa adalah :data:`Any`. Pemeriksa tipe statis akan memperlakukan setiap tipe sebagai dapat ditugaskan ke :data:`Any` dan :data:`Any` sebagai dapat ditugaskan ke setiap tipe.
This means that it is possible to perform any operation or method call on a value of type :data:`Any` and assign it to any variable::
Artinya, dimungkinkan untuk melakukan operasi atau pemanggilan metode apa pun pada sebuah nilai bertipe :data:`Any` dan menugaskannya ke variabel apa pun::
from typing import Any
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ''
s = a # OK
def foo(item: Any) -> int:
# Passes type checking; 'item' could be any type,
# and that type might have a 'bar' method
item.bar()
...
from typing import Any
a: Any = None
a = [] # OK
a = 2 # OK
s: str = ''
s = a # OK
def foo(item: Any) -> int:
# Passes type checking; 'item' could be any type,
# and that type might have a 'bar' method
item.bar()
...
Notice that no type checking is performed when assigning a value of type :data:`Any` to a more precise type. For example, the static type checker did not report an error when assigning ``a`` to ``s`` even though ``s`` was declared to be of type :class:`str` and receives an :class:`int` value at runtime!
Perlu diperhatikan bahwa tidak ada pemeriksaan tipe yang dilakukan saat menugaskan sebuah nilai bertipe :data:`Any` ke sebuah tipe yang lebih presisi. Sebagai contoh, pemeriksa tipe statis tidak melaporkan galat saat menugaskan ``a`` ke ``s`` meskipun ``s`` dideklarasikan bertipe :class:`str` dan menerima nilai :class:`int` pada saat runtime!
Furthermore, all functions without a return type or parameter types will implicitly default to using :data:`Any`::
Selain itu, semua fungsi tanpa tipe kembalian atau tipe parameter secara implisit akan menggunakan :data:`Any` sebagai default::
def legacy_parser(text):
...
return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
...
return data
def legacy_parser(text):
...
return data
# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
...
return data
This behavior allows :data:`Any` to be used as an *escape hatch* when you need to mix dynamically and statically typed code.
Perilaku ini memungkinkan :data:`Any` digunakan sebagai *escape hatch* ketika Anda perlu mencampur kode yang bertipe dinamis dan statis.
Contrast the behavior of :data:`Any` with the behavior of :class:`object`. Similar to :data:`Any`, every type is a subtype of :class:`object`. However, unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a subtype of every other type.
Bandingkan perilaku :data:`Any` dengan perilaku :class:`object`. Serupa dengan :data:`Any`, setiap tipe adalah subtipe dari :class:`object`. Namun, tidak seperti :data:`Any`, kebalikannya tidak benar: :class:`object` *bukan* subtipe dari setiap tipe lainnya.
That means when the type of a value is :class:`object`, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example::
Artinya, ketika tipe sebuah nilai adalah :class:`object`, pemeriksa tipe akan menolak hampir semua operasi terhadapnya, dan menugaskannya ke sebuah variabel (atau menggunakannya sebagai nilai kembalian) dari tipe yang lebih terspesialisasi adalah sebuah kesalahan tipe. Sebagai contoh::
def hash_a(item: object) -> int:
# Fails type checking; an object does not have a 'magic' method.
item.magic()
...
def hash_b(item: Any) -> int:
# Passes type checking
item.magic()
...
# Passes type checking, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Passes type checking, since Any is assignable to all types
hash_b(42)
hash_b("foo")
def hash_a(item: object) -> int:
# Fails type checking; an object does not have a 'magic' method.
item.magic()
...
def hash_b(item: Any) -> int:
# Passes type checking
item.magic()
...
# Passes type checking, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")
# Passes type checking, since Any is assignable to all types
hash_b(42)
hash_b("foo")
Use :class:`object` to indicate that a value could be any type in a typesafe manner. Use :data:`Any` to indicate that a value is dynamically typed.
Gunakan :class:`object` untuk menunjukkan bahwa sebuah nilai dapat bertipe apa pun dengan cara yang aman terhadap tipe. Gunakan :data:`Any` untuk menunjukkan bahwa sebuah nilai bertipe dinamis.
Nominal vs structural subtyping
Subtyping nominal vs struktural
Initially :pep:`484` defined the Python static type system as using *nominal subtyping*. This means that a class ``A`` is allowed where a class ``B`` is expected if and only if ``A`` is a subclass of ``B``.
Awalnya :pep:`484` mendefinisikan sistem tipe statis Python sebagai menggunakan *nominal subtyping*. Ini berarti sebuah kelas ``A`` diizinkan di tempat kelas ``B`` diharapkan jika dan hanya jika ``A`` adalah subkelas dari ``B``.
This requirement previously also applied to abstract base classes, such as :class:`~collections.abc.Iterable`. The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to :pep:`484`::
Persyaratan ini sebelumnya juga berlaku untuk kelas dasar abstrak, seperti :class:`~collections.abc.Iterable`. Masalah dengan pendekatan ini adalah sebuah kelas harus ditandai secara eksplisit untuk mendukungnya, yang tidak pythonic dan berbeda dari apa yang biasanya dilakukan dalam kode Python yang bertipe dinamis dan idiomatis. Sebagai contoh, kode ini sesuai dengan :pep:`484`::
from collections.abc import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]):
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
from collections.abc import Sized, Iterable, Iterator
class Bucket(Sized, Iterable[int]):
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
:pep:`544` solves this problem by allowing users to write the above code without explicit base classes in the class definition, allowing ``Bucket`` to be implicitly considered a subtype of both ``Sized`` and ``Iterable[int]`` by static type checkers. This is known as *structural subtyping* (or static duck-typing)::
:pep:`544` menyelesaikan masalah ini dengan mengizinkan pengguna menulis kode di atas tanpa kelas dasar eksplisit dalam definisi kelas, sehingga ``Bucket`` secara implisit dianggap sebagai subtipe dari ``Sized`` dan ``Iterable[int]`` oleh pemeriksa tipe statis. Hal ini dikenal sebagai *structural subtyping* (atau static duck-typing)::
from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket()) # Passes type check
from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket()) # Passes type check
Moreover, by subclassing a special class :class:`Protocol`, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).
Selain itu, dengan membuat subkelas dari kelas khusus :class:`Protocol`, pengguna dapat mendefinisikan protokol kustom baru untuk sepenuhnya menikmati structural subtyping (lihat contoh di bawah).
Module contents
Isi modul
The ``typing`` module defines the following classes, functions and decorators.
Modul ``typing`` mendefinisikan kelas, fungsi, dan dekorator berikut.
Special typing primitives
Primitif typing khusus
Special types
Tipe khusus
These can be used as types in annotations. They do not support subscription using ``[]``.
Tipe-tipe ini dapat digunakan sebagai tipe dalam anotasi. Tipe-tipe ini tidak mendukung subscription menggunakan ``[]``.
Special type indicating an unconstrained type.
Tipe khusus yang menunjukkan sebuah tipe yang tidak dibatasi.
Every type is assignable to :data:`Any`.
Setiap tipe dapat di-assign ke :data:`Any`.
:data:`Any` is assignable to every type.
:data:`Any` dapat di-assign ke setiap tipe.
:data:`Any` can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.
:data:`Any` kini dapat digunakan sebagai kelas dasar. Hal ini berguna untuk menghindari galat pemeriksa tipe pada kelas yang dapat melakukan duck typing di mana saja atau sangat dinamis.
A :ref:`constrained type variable <typing-constrained-typevar>`.
Sebuah :ref:`type variable yang dibatasi <typing-constrained-typevar>`.
Definition::
Definisi::
AnyStr = TypeVar('AnyStr', str, bytes)
AnyStr = TypeVar('AnyStr', str, bytes)
``AnyStr`` is meant to be used for functions that may accept :class:`str` or :class:`bytes` arguments but cannot allow the two to mix.
``AnyStr`` dimaksudkan untuk digunakan pada fungsi yang dapat menerima argumen :class:`str` atau :class:`bytes`, tetapi tidak mengizinkan keduanya bercampur.
For example::
Sebagai contoh::
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
return a + b
concat("foo", "bar") # OK, output has type 'str'
concat(b"foo", b"bar") # OK, output has type 'bytes'
concat("foo", b"bar") # Error, cannot mix str and bytes
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
return a + b
concat("foo", "bar") # OK, output has type 'str'
concat(b"foo", b"bar") # OK, output has type 'bytes'
concat("foo", b"bar") # Error, cannot mix str and bytes
Note that, despite its name, ``AnyStr`` has nothing to do with the :class:`Any` type, nor does it mean "any string". In particular, ``AnyStr`` and ``str | bytes`` are different from each other and have different use cases::
Perlu diperhatikan bahwa, meskipun namanya demikian, ``AnyStr`` tidak ada hubungannya dengan tipe :class:`Any`, dan juga tidak berarti "any string". Secara khusus, ``AnyStr`` dan ``str | bytes`` berbeda satu sama lain dan memiliki kasus penggunaan yang berbeda::
# Invalid use of AnyStr:
# The type variable is used only once in the function signature,
# so cannot be "solved" by the type checker
def greet_bad(cond: bool) -> AnyStr:
return "hi there!" if cond else b"greetings!"
# The better way of annotating this function:
def greet_proper(cond: bool) -> str | bytes:
return "hi there!" if cond else b"greetings!"
# Invalid use of AnyStr:
# The type variable is used only once in the function signature,
# so cannot be "solved" by the type checker
def greet_bad(cond: bool) -> AnyStr:
return "hi there!" if cond else b"greetings!"
# The better way of annotating this function:
def greet_proper(cond: bool) -> str | bytes:
return "hi there!" if cond else b"greetings!"
Deprecated in favor of the new :ref:`type parameter syntax <type-params>`. Use ``class A[T: (str, bytes)]: ...`` instead of importing ``AnyStr``. See :pep:`695` for more details.
Sudah tidak disarankan lagi dan digantikan oleh :ref:`sintaks parameter type <type-params>` yang baru. Gunakan ``class A[T: (str, bytes)]: ...`` alih-alih mengimpor ``AnyStr``. Lihat :pep:`695` untuk detailnya.
In Python 3.16, ``AnyStr`` will be removed from ``typing.__all__``, and deprecation warnings will be emitted at runtime when it is accessed or imported from ``typing``. ``AnyStr`` will be removed from ``typing`` in Python 3.18.
Pada Python 3.16, ``AnyStr`` akan dihapus dari ``typing.__all__``, dan peringatan pengusangan akan dimunculkan saat runtime ketika diakses atau diimpor dari ``typing``. ``AnyStr`` akan dihapus dari ``typing`` pada Python 3.18.
Special type that includes only literal strings.
Tipe khusus yang hanya mencakup string literal.
Any string literal is compatible with ``LiteralString``, as is another ``LiteralString``. However, an object typed as just ``str`` is not. A string created by composing ``LiteralString``-typed objects is also acceptable as a ``LiteralString``.
Setiap string literal kompatibel dengan ``LiteralString``, begitu pula ``LiteralString`` lainnya. Namun, objek yang bertipe ``str`` saja tidak kompatibel. String yang dibuat dengan menggabungkan objek bertipe ``LiteralString`` juga dapat diterima sebagai ``LiteralString``.
Example:
Contoh:
def run_query(sql: LiteralString) -> None:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
def run_query(sql: LiteralString) -> None:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
``LiteralString`` is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.
``LiteralString`` berguna untuk API sensitif yang mana string sembarang buatan pengguna dapat menimbulkan masalah. Misalnya, kedua kasus di atas yang menghasilkan galat pemeriksa tipe dapat rentan terhadap serangan SQL injection.
See :pep:`675` for more details.
Lihat :pep:`675` untuk detailnya.
:data:`!Never` and :data:`!NoReturn` represent the `bottom type <https://en.wikipedia.org/wiki/Bottom_type>`_, a type that has no members.
:data:`!Never` dan :data:`!NoReturn` merepresentasikan `bottom type <https://en.wikipedia.org/wiki/Bottom_type>`_, sebuah tipe yang tidak memiliki anggota.
They can be used to indicate that a function never returns, such as :func:`sys.exit`::
Keduanya dapat digunakan untuk menunjukkan bahwa sebuah fungsi tidak pernah mengembalikan nilai, seperti :func:`sys.exit`::
from typing import Never # or NoReturn
def stop() -> Never:
raise RuntimeError('no way')
from typing import Never # or NoReturn
def stop() -> Never:
raise RuntimeError('no way')
Or to define a function that should never be called, as there are no valid arguments, such as :func:`assert_never`::
Atau untuk mendefinisikan fungsi yang tidak boleh dipanggil, karena tidak ada argumen yang valid, seperti :func:`assert_never`::
from typing import Never # or NoReturn
def never_call_me(arg: Never) -> None:
pass
def int_or_str(arg: int | str) -> None:
never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never (or NoReturn)
from typing import Never # or NoReturn
def never_call_me(arg: Never) -> None:
pass
def int_or_str(arg: int | str) -> None:
never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never (or NoReturn)
:data:`!Never` and :data:`!NoReturn` have the same meaning in the type system and static type checkers treat both equivalently.
:data:`!Never` dan :data:`!NoReturn` memiliki arti yang sama dalam sistem tipe, dan pemeriksa tipe statis memperlakukan keduanya secara setara.
Added :data:`NoReturn`.
:data:`NoReturn` ditambahkan.
Added :data:`Never`.
:data:`Never` ditambahkan.
Special type to represent the current enclosed class.
Tipe khusus untuk merepresentasikan kelas yang sedang dilingkupi saat ini.
from typing import Self, reveal_type
class Foo:
def return_self(self) -> Self:
...
return self
class SubclassOfFoo(Foo): pass
reveal_type(Foo().return_self()) # Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self()) # Revealed type is "SubclassOfFoo"
from typing import Self, reveal_type
class Foo:
def return_self(self) -> Self:
...
return self
class SubclassOfFoo(Foo): pass
reveal_type(Foo().return_self()) # Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self()) # Revealed type is "SubclassOfFoo"
This annotation is semantically equivalent to the following, albeit in a more succinct fashion::
Anotasi ini secara semantik setara dengan berikut ini, meskipun dalam bentuk yang lebih ringkas::
from typing import TypeVar
Self = TypeVar("Self", bound="Foo")
class Foo:
def return_self(self: Self) -> Self:
...
return self
from typing import TypeVar
Self = TypeVar("Self", bound="Foo")
class Foo:
def return_self(self: Self) -> Self:
...
return self
In general, if something returns ``self``, as in the above examples, you should use ``Self`` as the return annotation. If ``Foo.return_self`` was annotated as returning ``"Foo"``, then the type checker would infer the object returned from ``SubclassOfFoo.return_self`` as being of type ``Foo`` rather than ``SubclassOfFoo``.
Secara umum, jika sesuatu mengembalikan ``self``, seperti dalam contoh di atas, Anda sebaiknya menggunakan ``Self`` sebagai anotasi return. Jika ``Foo.return_self`` dianotasi sebagai mengembalikan ``"Foo"``, maka pemeriksa tipe akan menyimpulkan objek yang dikembalikan dari ``SubclassOfFoo.return_self`` sebagai bertipe ``Foo``, bukan ``SubclassOfFoo``.
Other common use cases include:
Kasus penggunaan umum lainnya meliputi:
:class:`classmethod`\s that are used as alternative constructors and return instances of the ``cls`` parameter.
:class:`classmethod` yang digunakan sebagai konstruktor alternatif dan mengembalikan instance dari parameter ``cls``.
Annotating an :meth:`~object.__enter__` method which returns self.
Menganotasi metode :meth:`~object.__enter__` yang mengembalikan self.
You should not use ``Self`` as the return annotation if the method is not guaranteed to return an instance of a subclass when the class is subclassed::
Anda sebaiknya tidak menggunakan ``Self`` sebagai anotasi return jika metode tidak dijamin mengembalikan instance dari sebuah subkelas ketika kelas tersebut dibuat subkelas::
class Eggs:
# Self would be an incorrect return annotation here,
# as the object returned is always an instance of Eggs,
# even in subclasses
def returns_eggs(self) -> "Eggs":
return Eggs()
class Eggs:
# Self would be an incorrect return annotation here,
# as the object returned is always an instance of Eggs,
# even in subclasses
def returns_eggs(self) -> "Eggs":
return Eggs()
See :pep:`673` for more details.
Lihat :pep:`673` untuk detailnya.
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
Anotasi khusus untuk mendeklarasikan secara eksplisit sebuah :ref:`type alias <type-aliases>`.
from typing import TypeAlias
Factors: TypeAlias = list[int]
from typing import TypeAlias
Factors: TypeAlias = list[int]
``TypeAlias`` is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:
``TypeAlias`` sangat berguna pada versi Python yang lebih lama untuk menganotasi alias yang menggunakan forward reference, karena pemeriksa tipe mungkin sulit membedakan alias tersebut dari assignment variabel biasa:
from typing import Generic, TypeAlias, TypeVar
T = TypeVar("T")
# "Box" does not exist yet,
# so we have to use quotes for the forward reference on Python <3.12.
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
# not a variable assignment to a string.
BoxOfStrings: TypeAlias = "Box[str]"
class Box(Generic[T]):
@classmethod
def make_box_of_strings(cls) -> BoxOfStrings: ...
from typing import Generic, TypeAlias, TypeVar
T = TypeVar("T")
# "Box" does not exist yet,
# so we have to use quotes for the forward reference on Python <3.12.
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
# not a variable assignment to a string.
BoxOfStrings: TypeAlias = "Box[str]"
class Box(Generic[T]):
@classmethod
def make_box_of_strings(cls) -> BoxOfStrings: ...
See :pep:`613` for more details.
Lihat :pep:`613` untuk detailnya.
:data:`TypeAlias` is deprecated in favor of the :keyword:`type` statement, which creates instances of :class:`TypeAliasType` and which natively supports forward references. Note that while :data:`TypeAlias` and :class:`TypeAliasType` serve similar purposes and have similar names, they are distinct and the latter is not the type of the former. Removal of :data:`TypeAlias` is not currently planned, but users are encouraged to migrate to :keyword:`type` statements.
:data:`TypeAlias` sudah tidak disarankan lagi dan digantikan oleh statement :keyword:`type`, yang membuat instance dari :class:`TypeAliasType` dan secara bawaan mendukung forward reference. Perlu diperhatikan bahwa meskipun :data:`TypeAlias` dan :class:`TypeAliasType` memiliki tujuan yang serupa dan nama yang mirip, keduanya berbeda dan yang terakhir bukanlah tipe dari yang pertama. Penghapusan :data:`TypeAlias` saat ini belum direncanakan, tetapi pengguna dianjurkan untuk bermigrasi ke statement :keyword:`type`.
Special forms
Bentuk khusus
These can be used as types in annotations. They all support subscription using ``[]``, but each has a unique syntax.
Bentuk-bentuk ini dapat digunakan sebagai tipe dalam anotasi. Semuanya mendukung subscription menggunakan ``[]``, tetapi masing-masing memiliki sintaks yang unik.
Union type; ``Union[X, Y]`` is equivalent to ``X | Y`` and means either X or Y.
Tipe union; ``Union[X, Y]`` setara dengan ``X | Y`` dan berarti X atau Y.
To define a union, use e.g. ``Union[int, str]`` or the shorthand ``int | str``. Using that shorthand is recommended. Details:
Untuk mendefinisikan sebuah union, gunakan misalnya ``Union[int, str]`` atau bentuk singkat ``int | str``. Menggunakan bentuk singkat tersebut dianjurkan. Detail:
The arguments must be types and there must be at least one.
Argumen harus berupa tipe dan harus ada setidaknya satu.
Unions of unions are flattened, e.g.::
Union dari union diratakan, misalnya::
Union[Union[int, str], float] == Union[int, str, float]
Union[Union[int, str], float] == Union[int, str, float]
However, this does not apply to unions referenced through a type alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::
Namun, hal ini tidak berlaku untuk union yang direferensikan melalui sebuah alias tipe, untuk menghindari pemaksaan evaluasi :class:`TypeAliasType` yang mendasarinya::
type A = Union[int, str]
Union[A, float] != Union[int, str, float]
type A = Union[int, str]
Union[A, float] != Union[int, str, float]
Unions of a single argument vanish, e.g.::
Union dengan satu argumen akan hilang, misalnya::
Union[int] == int # The constructor actually returns int
Union[int] == int # The constructor actually returns int
Redundant arguments are skipped, e.g.::
Argumen yang redundan dilewati, misalnya::
Union[int, str, int] == Union[int, str] == int | str
Union[int, str, int] == Union[int, str] == int | str
When comparing unions, the argument order is ignored, e.g.::
Saat membandingkan union, urutan argumen diabaikan, misalnya::
Union[int, str] == Union[str, int]
Union[int, str] == Union[str, int]
You cannot subclass or instantiate a ``Union``.
Anda tidak dapat membuat subkelas atau menginstansiasi sebuah ``Union``.
You cannot write ``Union[X][Y]``.
Anda tidak dapat menulis ``Union[X][Y]``.
Don't remove explicit subclasses from unions at runtime.
Jangan menghapus subkelas eksplisit dari union saat runtime.
Unions can now be written as ``X | Y``. See :ref:`union type expressions<types-union>`.
Union kini dapat ditulis sebagai ``X | Y``. Lihat :ref:`ekspresi type union <types-union>`.
:class:`types.UnionType` is now an alias for :class:`Union`, and both ``Union[int, str]`` and ``int | str`` create instances of the same class. To check whether an object is a ``Union`` at runtime, use ``isinstance(obj, Union)``. For compatibility with earlier versions of Python, use ``get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType``.
:class:`types.UnionType` kini merupakan alias untuk :class:`Union`, dan ``Union[int, str]`` maupun ``int | str`` membuat instance dari kelas yang sama. Untuk memeriksa apakah sebuah objek adalah ``Union`` saat runtime, gunakan ``isinstance(obj, Union)``. Untuk kompatibilitas dengan versi Python yang lebih lama, gunakan ``get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType``.
``Optional[X]`` is equivalent to ``X | None`` (or ``Union[X, None]``).
``Optional[X]`` setara dengan ``X | None`` (atau ``Union[X, None]``).
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the ``Optional`` qualifier on its type annotation just because it is optional. For example::
Perlu diperhatikan bahwa ini bukan konsep yang sama dengan argumen opsional, yaitu argumen yang memiliki nilai default. Argumen opsional yang memiliki nilai default tidak memerlukan qualifier ``Optional`` pada anotasi tipe-nya hanya karena argumen tersebut bersifat opsional. Misalnya::
def foo(arg: int = 0) -> None:
...
def foo(arg: int = 0) -> None:
...
On the other hand, if an explicit value of ``None`` is allowed, the use of ``Optional`` is appropriate, whether the argument is optional or not. For example::
Di sisi lain, jika nilai ``None`` yang eksplisit diizinkan, penggunaan ``Optional`` sudah tepat, baik argumen tersebut bersifat opsional maupun tidak. Misalnya::
def foo(arg: Optional[int] = None) -> None:
...
def foo(arg: Optional[int] = None) -> None:
...
Optional can now be written as ``X | None``. See :ref:`union type expressions<types-union>`.
Optional kini dapat ditulis sebagai ``X | None``. Lihat :ref:`ekspresi type union <types-union>`.
Special form for annotating higher-order functions.
Bentuk khusus untuk menganotasi fungsi orde tinggi.
``Concatenate`` can be used in conjunction with :ref:`Callable <annotating-callables>` and :class:`ParamSpec` to annotate a higher-order callable which adds, removes, or transforms parameters of another callable. Usage is in the form ``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate`` is valid when used in :ref:`Callable <annotating-callables>` type hints and when instantiating user-defined generic classes with :class:`ParamSpec` parameters. The last parameter to ``Concatenate`` must be a :class:`ParamSpec` or ellipsis (``...``).
``Concatenate`` dapat digunakan bersama :ref:`Callable <annotating-callables>` dan :class:`ParamSpec` untuk menganotasi sebuah callable orde tinggi yang menambahkan, menghapus, atau mentransformasi parameter dari callable lain. Penggunaannya berbentuk ``Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]``. ``Concatenate`` valid bila digunakan dalam hint tipe :ref:`Callable <annotating-callables>` dan saat menginstansiasi kelas generik yang didefinisikan pengguna dengan parameter :class:`ParamSpec`. Parameter terakhir untuk ``Concatenate`` harus berupa sebuah :class:`ParamSpec` atau elipsis (``...``).
For example, to annotate a decorator ``with_lock`` which provides a :class:`threading.Lock` to the decorated function, ``Concatenate`` can be used to indicate that ``with_lock`` expects a callable which takes in a ``Lock`` as the first argument, and returns a callable with a different type signature. In this case, the :class:`ParamSpec` indicates that the returned callable's parameter types are dependent on the parameter types of the callable being passed in::
Sebagai contoh, untuk menganotasi sebuah dekorator ``with_lock`` yang menyediakan :class:`threading.Lock` ke fungsi yang didekorasi, ``Concatenate`` dapat digunakan untuk menunjukkan bahwa ``with_lock`` mengharapkan sebuah callable yang menerima ``Lock`` sebagai argumen pertama, dan mengembalikan callable dengan signatur tipe yang berbeda. Dalam kasus ini, :class:`ParamSpec` menunjukkan bahwa parameter tipe dari callable yang dikembalikan bergantung pada parameter tipe dari callable yang diteruskan::
from collections.abc import Callable
from threading import Lock
from typing import Concatenate
# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()
def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
'''A type-safe decorator which provides a lock.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> R:
# Provide the lock as the first argument.
return f(my_lock, *args, **kwargs)
return inner
@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
'''Add a list of numbers together in a thread-safe manner.'''
with lock:
return sum(numbers)
# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])
from collections.abc import Callable
from threading import Lock
from typing import Concatenate
# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()
def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
'''A type-safe decorator which provides a lock.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> R:
# Provide the lock as the first argument.
return f(my_lock, *args, **kwargs)
return inner
@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
'''Add a list of numbers together in a thread-safe manner.'''
with lock:
return sum(numbers)
# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])
:pep:`612` -- Parameter Specification Variables (the PEP which introduced ``ParamSpec`` and ``Concatenate``)
:pep:`612` -- Parameter Specification Variables (PEP yang memperkenalkan ``ParamSpec`` dan ``Concatenate``)
:class:`ParamSpec`
:class:`ParamSpec`
:ref:`annotating-callables`
:ref:`annotating-callables`
Special typing form to define "literal types".
Bentuk typing khusus untuk mendefinisikan "literal tipe".
``Literal`` can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals.
``Literal`` dapat digunakan untuk menunjukkan kepada pemeriksa tipe bahwa objek yang dianotasi memiliki nilai yang setara dengan salah satu literal yang diberikan.
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
``Literal[...]`` cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to ``Literal[...]``, but type checkers may impose restrictions. See :pep:`586` for more details about literal types.
``Literal[...]`` tidak dapat dibuat subkelasnya. Saat runtime, nilai sembarang diizinkan sebagai argumen tipe untuk ``Literal[...]``, tetapi pemeriksa tipe dapat memberlakukan pembatasan. Lihat :pep:`586` untuk detail lebih lanjut tentang literal tipe.
Additional details:
Detail tambahan:
The arguments must be literal values and there must be at least one.
Argumen harus berupa nilai literal dan harus ada setidaknya satu.
Nested ``Literal`` types are flattened, e.g.::
Tipe ``Literal`` yang bersarang diratakan, misalnya::
assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]
assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]
However, this does not apply to ``Literal`` types referenced through a type alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::
Namun, hal ini tidak berlaku untuk tipe ``Literal`` yang direferensikan melalui sebuah alias tipe, untuk menghindari pemaksaan evaluasi :class:`TypeAliasType` yang mendasarinya::
type A = Literal[1, 2]
assert Literal[A, 3] != Literal[1, 2, 3]
type A = Literal[1, 2]
assert Literal[A, 3] != Literal[1, 2, 3]
assert Literal[1, 2, 1] == Literal[1, 2]
assert Literal[1, 2, 1] == Literal[1, 2]
When comparing literals, the argument order is ignored, e.g.::
Saat membandingkan literal, urutan argumen diabaikan, misalnya::
assert Literal[1, 2] == Literal[2, 1]
assert Literal[1, 2] == Literal[2, 1]
You cannot subclass or instantiate a ``Literal``.
Anda tidak dapat membuat subkelas atau menginstansiasi sebuah ``Literal``.
You cannot write ``Literal[X][Y]``.
Anda tidak dapat menulis ``Literal[X][Y]``.
``Literal`` now de-duplicates parameters. Equality comparisons of ``Literal`` objects are no longer order dependent. ``Literal`` objects will now raise a :exc:`TypeError` exception during equality comparisons if one of their parameters are not :term:`hashable`.
``Literal`` kini menghapus parameter yang duplikat. Perbandingan kesetaraan objek ``Literal`` tidak lagi bergantung pada urutan. Objek ``Literal`` kini akan memunculkan eksepsi :exc:`TypeError` selama perbandingan kesetaraan jika salah satu parameternya bukan :term:`hashable`.
Special type construct to mark class variables.
Konstruk tipe khusus untuk menandai variabel kelas.
As introduced in :pep:`526`, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage::
Sebagaimana diperkenalkan dalam :pep:`526`, anotasi variabel yang dibungkus dalam ClassVar menunjukkan bahwa sebuah atribut dimaksudkan untuk digunakan sebagai variabel kelas dan tidak boleh di-set pada instance dari kelas tersebut. Penggunaan::
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
:data:`ClassVar` accepts only types and cannot be further subscribed.
:data:`ClassVar` hanya menerima tipe dan tidak dapat di-subscript lagi.
:data:`ClassVar` is not a class itself, and cannot be used with :func:`isinstance` or :func:`issubclass`. :data:`ClassVar` does not change Python runtime behavior, but it can be used by static type checkers. For example, a type checker might flag the following code as an error::
:data:`ClassVar` bukan sebuah kelas, dan tidak dapat digunakan dengan :func:`isinstance` atau :func:`issubclass`. :data:`ClassVar` tidak mengubah perilaku runtime Python, tetapi dapat digunakan oleh pemeriksa tipe statis. Misalnya, sebuah pemeriksa tipe mungkin menandai kode berikut sebagai galat::
enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {} # This is OK
enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {} # This is OK
:data:`ClassVar` can now be nested in :data:`Final` and vice versa.
:data:`ClassVar` kini dapat bersarang dalam :data:`Final` dan sebaliknya.
Special typing construct to indicate final names to type checkers.
Konstruk typing khusus untuk menunjukkan nama final kepada pemeriksa tipe.
Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.
Nama final tidak dapat di-assign ulang dalam scope apa pun. Nama final yang dideklarasikan dalam lingkup kelas tidak dapat di-override dalam subkelas.
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
There is no runtime checking of these properties. See :pep:`591` for more details.
Tidak ada pemeriksaan runtime terhadap properti-properti ini. Lihat :pep:`591` untuk detailnya.
:data:`Final` can now be nested in :data:`ClassVar` and vice versa.
:data:`Final` kini dapat bersarang dalam :data:`ClassVar` dan sebaliknya.
Special typing construct to mark a :class:`TypedDict` key as required.
Konstruk typing khusus untuk menandai sebuah kunci :class:`TypedDict` sebagai wajib.
This is mainly useful for ``total=False`` TypedDicts. See :class:`TypedDict` and :pep:`655` for more details.
Hal ini terutama berguna untuk TypedDict dengan ``total=False``. Lihat :class:`TypedDict` dan :pep:`655` untuk detailnya.
Special typing construct to mark a :class:`TypedDict` key as potentially missing.
Konstruk typing khusus untuk menandai sebuah kunci :class:`TypedDict` sebagai berpotensi tidak ada.
See :class:`TypedDict` and :pep:`655` for more details.
Lihat :class:`TypedDict` dan :pep:`655` untuk detailnya.
A special typing construct to mark an item of a :class:`TypedDict` as read-only.
Konstruk typing khusus untuk menandai sebuah item dari :class:`TypedDict` sebagai read-only.
class Movie(TypedDict):
title: ReadOnly[str]
year: int
def mutate_movie(m: Movie) -> None:
m["year"] = 1999 # allowed
m["title"] = "The Matrix" # type checker error
class Movie(TypedDict):
title: ReadOnly[str]
year: int
def mutate_movie(m: Movie) -> None:
m["year"] = 1999 # allowed
m["title"] = "The Matrix" # type checker error
There is no runtime checking for this property.
Tidak ada pemeriksaan runtime untuk properti ini.
See :class:`TypedDict` and :pep:`705` for more details.
Lihat :class:`TypedDict` dan :pep:`705` untuk detailnya.
Special typing form to add context-specific metadata to an annotation.
Bentuk typing khusus untuk menambahkan metadata yang spesifik konteks ke sebuah anotasi.
Add metadata ``x`` to a given type ``T`` by using the annotation ``Annotated[T, x]``. Metadata added using ``Annotated`` can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a :attr:`!__metadata__` attribute.
Tambahkan metadata ``x`` ke sebuah tipe ``T`` tertentu dengan menggunakan anotasi ``Annotated[T, x]``. Metadata yang ditambahkan menggunakan ``Annotated`` dapat digunakan oleh perkakas analisis statis atau saat runtime. Saat runtime, metadata disimpan dalam atribut :attr:`!__metadata__`.
If a library or tool encounters an annotation ``Annotated[T, x]`` and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as ``T``. As such, ``Annotated`` can be useful for code that wants to use annotations for purposes outside Python's static typing system.
Jika sebuah library atau perkakas menemukan anotasi ``Annotated[T, x]`` dan tidak memiliki logika khusus untuk metadata tersebut, tool tersebut sebaiknya mengabaikan metadata dan sekadar memperlakukan anotasi sebagai ``T``. Dengan demikian, ``Annotated`` dapat berguna untuk kode yang ingin menggunakan anotasi untuk keperluan di luar sistem typing statis Python.
Using ``Annotated[T, x]`` as an annotation still allows for static typechecking of ``T``, as type checkers will simply ignore the metadata ``x``. In this way, ``Annotated`` differs from the :deco:`no_type_check` decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.
Menggunakan ``Annotated[T, x]`` sebagai anotasi tetap memungkinkan typechecking statis atas ``T``, karena pemeriksa tipe akan sekadar mengabaikan metadata ``x``. Dengan cara ini, ``Annotated`` berbeda dari dekorator :deco:`no_type_check`, yang juga dapat digunakan untuk menambahkan anotasi di luar cakupan sistem typing, tetapi sepenuhnya menonaktifkan typechecking untuk sebuah fungsi atau kelas.
The responsibility of how to interpret the metadata lies with the tool or library encountering an ``Annotated`` annotation. A tool or library encountering an ``Annotated`` type can scan through the metadata elements to determine if they are of interest (e.g., using :func:`isinstance`).
Tanggung jawab atas cara menafsirkan metadata berada pada perkakas atau library yang menemukan anotasi ``Annotated``. Perkakas atau library yang menemukan sebuah tipe ``Annotated`` dapat memindai elemen-elemen metadata untuk menentukan apakah elemen tersebut menarik (misalnya, menggunakan :func:`isinstance`).
Here is an example of how you might use ``Annotated`` to add metadata to type annotations if you were doing range analysis:
Berikut adalah contoh bagaimana Anda dapat menggunakan ``Annotated`` untuk menambahkan metadata ke anotasi tipe jika Anda sedang melakukan analisis rentang:
@dataclass
class ValueRange:
lo: int
hi: int
T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
@dataclass
class ValueRange:
lo: int
hi: int
T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]
The first argument to ``Annotated`` must be a valid type. Multiple metadata elements can be supplied as ``Annotated`` supports variadic arguments. The order of the metadata elements is preserved and matters for equality checks::
Argumen pertama untuk ``Annotated`` harus berupa tipe yang valid. Beberapa elemen metadata dapat diberikan karena ``Annotated`` mendukung argumen variadic. Urutan elemen metadata dipertahankan dan berpengaruh pada pemeriksaan kesetaraan::
@dataclass
class ctype:
kind: str
a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]
assert a1 != a2 # Order matters
@dataclass
class ctype:
kind: str
a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]
assert a1 != a2 # Order matters
It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.
Terserah kepada perkakas yang mengonsumsi anotasi untuk memutuskan apakah klien diizinkan menambahkan beberapa elemen metadata ke satu anotasi dan bagaimana menggabungkan anotasi-anotasi tersebut.
Nested ``Annotated`` types are flattened. The order of the metadata elements starts with the innermost annotation::
Tipe ``Annotated`` yang bersarang diratakan. Urutan elemen metadata dimulai dari anotasi yang paling dalam::
assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
int, ValueRange(3, 10), ctype("char")
]
assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
int, ValueRange(3, 10), ctype("char")
]
However, this does not apply to ``Annotated`` types referenced through a type alias, to avoid forcing evaluation of the underlying :class:`TypeAliasType`::
Namun, hal ini tidak berlaku untuk tipe ``Annotated`` yang direferensikan melalui sebuah alias tipe, untuk menghindari pemaksaan evaluasi :class:`TypeAliasType` yang mendasarinya::
type From3To10[T] = Annotated[T, ValueRange(3, 10)]
assert Annotated[From3To10[int], ctype("char")] != Annotated[
int, ValueRange(3, 10), ctype("char")
]
type From3To10[T] = Annotated[T, ValueRange(3, 10)]
assert Annotated[From3To10[int], ctype("char")] != Annotated[
int, ValueRange(3, 10), ctype("char")
]
Duplicated metadata elements are not removed::
Elemen metadata yang duplikat tidak dihapus::
assert Annotated[int, ValueRange(3, 10)] != Annotated[
int, ValueRange(3, 10), ValueRange(3, 10)
]
assert Annotated[int, ValueRange(3, 10)] != Annotated[
int, ValueRange(3, 10), ValueRange(3, 10)
]
``Annotated`` can be used with nested and generic aliases:
``Annotated`` dapat digunakan dengan alias yang bersarang dan generik:
@dataclass
class MaxLen:
value: int
type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]
# When used in a type annotation, a type checker will treat "V" the same as
# ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
type V = Vec[int]
@dataclass
class MaxLen:
value: int
type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]
# When used in a type annotation, a type checker will treat "V" the same as
# ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
type V = Vec[int]
``Annotated`` cannot be used with an unpacked :class:`TypeVarTuple`::
``Annotated`` tidak dapat digunakan dengan :class:`TypeVarTuple` yang di-unpack::
type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1] # NOT valid
type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1] # NOT valid
where ``T1``, ``T2``, ... are :class:`TypeVars <TypeVar>`. This is invalid as only one type should be passed to Annotated.
dengan ``T1``, ``T2``, ... adalah :class:`TypeVars <TypeVar>`. Hal ini tidak valid karena hanya satu tipe yang boleh diteruskan ke Annotated.
By default, :func:`get_type_hints` strips the metadata from annotations. Pass ``include_extras=True`` to have the metadata preserved:
Secara default, :func:`get_type_hints` menghilangkan metadata dari anotasi. Teruskan ``include_extras=True`` agar metadata dipertahankan:
>>> from typing import Annotated, get_type_hints
>>> def func(x: Annotated[int, "metadata"]) -> None: pass
...
>>> get_type_hints(func)
{'x': <class 'int'>, 'return': <class 'NoneType'>}
>>> get_type_hints(func, include_extras=True)
{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}
>>> from typing import Annotated, get_type_hints
>>> def func(x: Annotated[int, "metadata"]) -> None: pass
...
>>> get_type_hints(func)
{'x': <class 'int'>, 'return': <class 'NoneType'>}
>>> get_type_hints(func, include_extras=True)
{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}
At runtime, the metadata associated with an ``Annotated`` type can be retrieved via the :attr:`!__metadata__` attribute:
Pada runtime, metadata yang terkait dengan tipe ``Annotated`` dapat diambil melalui atribut :attr:`!__metadata__`:
>>> from typing import Annotated
>>> X = Annotated[int, "very", "important", "metadata"]
>>> X
typing.Annotated[int, 'very', 'important', 'metadata']
>>> X.__metadata__
('very', 'important', 'metadata')
>>> from typing import Annotated
>>> X = Annotated[int, "very", "important", "metadata"]
>>> X
typing.Annotated[int, 'very', 'important', 'metadata']
>>> X.__metadata__
('very', 'important', 'metadata')
If you want to retrieve the original type wrapped by ``Annotated``, use the :attr:`!__origin__` attribute:
Jika Anda ingin mengambil tipe asli yang dibungkus oleh ``Annotated``, gunakan atribut :attr:`!__origin__`:
>>> from typing import Annotated, get_origin
>>> Password = Annotated[str, "secret"]
>>> Password.__origin__
<class 'str'>
>>> from typing import Annotated, get_origin
>>> Password = Annotated[str, "secret"]
>>> Password.__origin__
<class 'str'>
Note that using :func:`get_origin` will return ``Annotated`` itself:
Perlu diperhatikan bahwa menggunakan :func:`get_origin` akan mengembalikan ``Annotated`` itu sendiri:
>>> get_origin(Password)
typing.Annotated
>>> get_origin(Password)
typing.Annotated
:pep:`593` - Flexible function and variable annotations
:pep:`593` - Anotasi fungsi dan variabel yang fleksibel
The PEP introducing ``Annotated`` to the standard library.
PEP yang memperkenalkan ``Annotated`` ke pustaka standar.
A special form representing the value that results from evaluating a type expression.
Sebuah bentuk khusus yang merepresentasikan nilai yang dihasilkan dari evaluasi sebuah ekspresi tipe.
This value encodes the information supplied in the type expression, and it represents the type described by that type expression.
Nilai ini mengodekan informasi yang diberikan dalam ekspresi tipe, dan merepresentasikan tipe yang dideskripsikan oleh ekspresi tipe tersebut.
When used in a type expression, ``TypeForm`` describes a set of type form objects. It accepts a single type argument, which must be a valid type expression. ``TypeForm[T]`` describes the set of all type form objects that represent the type ``T`` or types assignable to ``T``.
Saat digunakan dalam sebuah ekspresi tipe, ``TypeForm`` mendeskripsikan sekumpulan objek bentuk tipe. Ia menerima satu argumen tipe, yang harus berupa ekspresi tipe yang valid. ``TypeForm[T]`` mendeskripsikan sekumpulan semua objek bentuk tipe yang merepresentasikan tipe ``T`` atau tipe yang dapat ditetapkan ke ``T``.
``TypeForm(obj)`` simply returns ``obj`` unchanged. This is useful for explicitly marking a value as a type form for static type checkers.
``TypeForm(obj)`` hanya mengembalikan ``obj`` tanpa perubahan. Hal ini berguna untuk menandai sebuah nilai secara eksplisit sebagai bentuk tipe bagi pemeriksa tipe statis.
Example::
Contoh::
from typing import Any, TypeForm
def cast[T](typ: TypeForm[T], value: Any) -> T: ...
reveal_type(cast(int, "x")) # Revealed type is "int"
from typing import Any, TypeForm
def cast[T](typ: TypeForm[T], value: Any) -> T: ...
reveal_type(cast(int, "x")) # Revealed type is "int"
See :pep:`747` for details.
Lihat :pep:`747` untuk detailnya.
Special typing construct for marking user-defined type predicate functions.
Konstruk typing khusus untuk menandai fungsi predikat tipe yang didefinisikan pengguna.
``TypeIs`` can be used to annotate the return type of a user-defined type predicate function. ``TypeIs`` only accepts a single type argument. At runtime, functions marked this way should return a boolean and take at least one positional argument.
``TypeIs`` dapat digunakan untuk menganotasi tipe kembalian dari sebuah fungsi predikat tipe yang didefinisikan pengguna. ``TypeIs`` hanya menerima satu argumen tipe. Pada runtime, fungsi yang ditandai dengan cara ini harus mengembalikan sebuah boolean dan menerima setidaknya satu argumen posisional.
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type predicate"::
``TypeIs`` bertujuan memanfaatkan *penyempitan tipe* -- sebuah teknik yang digunakan oleh pemeriksa tipe statis untuk menentukan tipe yang lebih presisi dari sebuah ekspresi dalam alur kode program. Biasanya penyempitan tipe dilakukan dengan menganalisis alur kode kondisional dan menerapkan penyempitan tersebut ke sebuah blok kode. Ekspresi kondisional di sini kadang disebut sebagai "predikat tipe"::
def is_str(val: str | float):
# "isinstance" type predicate
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...
def is_str(val: str | float):
# "isinstance" type predicate
if isinstance(val, str):
# Type of ``val`` is narrowed to ``str``
...
else:
# Else, type of ``val`` is narrowed to ``float``.
...
Sometimes it would be convenient to use a user-defined boolean function as a type predicate. Such a function should use ``TypeIs[...]`` or :data:`TypeGuard` as its return type to alert static type checkers to this intention. ``TypeIs`` usually has more intuitive behavior than ``TypeGuard``, but it cannot be used when the input and output types are incompatible (e.g., ``list[object]`` to ``list[int]``) or when the function does not return ``True`` for all instances of the narrowed type.
Kadang akan lebih mudah untuk menggunakan sebuah fungsi boolean yang didefinisikan pengguna sebagai predikat tipe. Fungsi semacam itu harus menggunakan ``TypeIs[...]`` atau :data:`TypeGuard` sebagai tipe kembaliannya untuk memberi tahu pemeriksa tipe statis tentang maksud tersebut. ``TypeIs`` biasanya memiliki perilaku yang lebih intuitif daripada ``TypeGuard``, tetapi tidak dapat digunakan ketika tipe input dan keluaran tidak kompatibel (misalnya, ``list[object]`` ke ``list[int]``) atau ketika fungsi tidak mengembalikan ``True`` untuk semua instance dari tipe yang dipersempit.
Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for a given function:
Menggunakan ``-> TypeIs[NarrowedType]`` memberi tahu pemeriksa tipe statis bahwa untuk sebuah fungsi tertentu:
The return value is a boolean.
Nilai kembaliannya adalah sebuah boolean.
If the return value is ``True``, the type of its argument is the intersection of the argument's original type and ``NarrowedType``.
Jika nilai kembaliannya adalah ``True``, tipe argumennya adalah irisan dari tipe asli argumen dan ``NarrowedType``.
If the return value is ``False``, the type of its argument is narrowed to exclude ``NarrowedType``.
Jika nilai kembaliannya adalah ``False``, tipe argumennya dipersempit untuk mengecualikan ``NarrowedType``.
from typing import assert_type, final, TypeIs
class Parent: pass
class Child(Parent): pass
@final
class Unrelated: pass
def is_parent(val: object) -> TypeIs[Parent]:
return isinstance(val, Parent)
def run(arg: Child | Unrelated):
if is_parent(arg):
# Type of ``arg`` is narrowed to the intersection
# of ``Parent`` and ``Child``, which is equivalent to
# ``Child``.
assert_type(arg, Child)
else:
# Type of ``arg`` is narrowed to exclude ``Parent``,
# so only ``Unrelated`` is left.
assert_type(arg, Unrelated)
from typing import assert_type, final, TypeIs
class Parent: pass
class Child(Parent): pass
@final
class Unrelated: pass
def is_parent(val: object) -> TypeIs[Parent]:
return isinstance(val, Parent)
def run(arg: Child | Unrelated):
if is_parent(arg):
# Type of ``arg`` is narrowed to the intersection
# of ``Parent`` and ``Child``, which is equivalent to
# ``Child``.
assert_type(arg, Child)
else:
# Type of ``arg`` is narrowed to exclude ``Parent``,
# so only ``Unrelated`` is left.
assert_type(arg, Unrelated)
The type inside ``TypeIs`` must be consistent with the type of the function's argument; if it is not, static type checkers will raise an error. An incorrectly written ``TypeIs`` function can lead to unsound behavior in the type system; it is the user's responsibility to write such functions in a type-safe manner.
Tipe di dalam ``TypeIs`` harus konsisten dengan tipe argumen fungsi; jika tidak, pemeriksa tipe statis akan memunculkan galat. Fungsi ``TypeIs`` yang ditulis secara tidak benar dapat menyebabkan perilaku yang tidak sound dalam sistem tipe; menulis fungsi semacam itu dengan cara yang aman terhadap tipe adalah tanggung jawab pengguna.
If a ``TypeIs`` function is a class or instance method, then the type in ``TypeIs`` maps to the type of the second parameter (after ``cls`` or ``self``).
Jika sebuah fungsi ``TypeIs`` adalah metode kelas atau instance, maka tipe dalam ``TypeIs`` dipetakan ke tipe parameter kedua (setelah ``cls`` atau ``self``).
In short, the form ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, means that if ``foo(arg)`` returns ``True``, then ``arg`` is an instance of ``TypeB``, and if it returns ``False``, it is not an instance of ``TypeB``.
Singkatnya, bentuk ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...`` berarti bahwa jika ``foo(arg)`` mengembalikan ``True``, maka ``arg`` adalah sebuah instance dari ``TypeB``, dan jika mengembalikan ``False``, maka ia bukan instance dari ``TypeB``.
``TypeIs`` also works with type variables. For more information, see :pep:`742` (Narrowing types with ``TypeIs``).
``TypeIs`` juga bekerja dengan variabel tipe. Untuk informasi lebih lanjut, lihat :pep:`742` (Mempersempit tipe dengan ``TypeIs``).
Type predicate functions are user-defined functions that return whether their argument is an instance of a particular type. ``TypeGuard`` works similarly to :data:`TypeIs`, but has subtly different effects on type checking behavior (see below).
Fungsi predikat tipe adalah fungsi yang didefinisikan pengguna yang mengembalikan apakah argumennya adalah sebuah instance dari tipe tertentu. ``TypeGuard`` bekerja mirip dengan :data:`TypeIs`, tetapi memiliki efek yang sedikit berbeda pada perilaku pengecekan tipe (lihat di bawah).
Using ``-> TypeGuard`` tells the static type checker that for a given function:
Menggunakan ``-> TypeGuard`` memberi tahu pemeriksa tipe statis bahwa untuk sebuah fungsi tertentu:
If the return value is ``True``, the type of its argument is the type inside ``TypeGuard``.
Jika nilai kembaliannya adalah ``True``, tipe argumennya adalah tipe di dalam ``TypeGuard``.
``TypeGuard`` also works with type variables. See :pep:`647` for more details.
``TypeGuard`` juga bekerja dengan variabel tipe. Lihat :pep:`647` untuk detail selengkapnya.
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
``TypeIs`` and ``TypeGuard`` differ in the following ways:
``TypeIs`` dan ``TypeGuard`` berbeda dalam hal-hal berikut:
``TypeIs`` requires the narrowed type to be a subtype of the input type, while ``TypeGuard`` does not. The main reason is to allow for things like narrowing ``list[object]`` to ``list[str]`` even though the latter is not a subtype of the former, since ``list`` is invariant.
``TypeIs`` mengharuskan tipe yang dipersempit menjadi subtipe dari tipe input, sedangkan ``TypeGuard`` tidak. Alasan utamanya adalah untuk memungkinkan hal-hal seperti mempersempit ``list[object]`` menjadi ``list[str]`` meskipun yang terakhir bukan subtipe dari yang pertama, karena ``list`` bersifat invarian.
When a ``TypeGuard`` function returns ``True``, type checkers narrow the type of the variable to exactly the ``TypeGuard`` type. When a ``TypeIs`` function returns ``True``, type checkers can infer a more precise type combining the previously known type of the variable with the ``TypeIs`` type. (Technically, this is known as an intersection type.)
Ketika sebuah fungsi ``TypeGuard`` mengembalikan ``True``, pemeriksa tipe mempersempit tipe variabel menjadi tepat tipe ``TypeGuard``. Ketika sebuah fungsi ``TypeIs`` mengembalikan ``True``, pemeriksa tipe dapat menyimpulkan tipe yang lebih presisi dengan menggabungkan tipe variabel yang sebelumnya diketahui dengan tipe ``TypeIs``. (Secara teknis, hal ini dikenal sebagai tipe irisan.)
When a ``TypeGuard`` function returns ``False``, type checkers cannot narrow the type of the variable at all. When a ``TypeIs`` function returns ``False``, type checkers can narrow the type of the variable to exclude the ``TypeIs`` type.
Ketika sebuah fungsi ``TypeGuard`` mengembalikan ``False``, pemeriksa tipe tidak dapat mempersempit tipe variabel sama sekali. Ketika sebuah fungsi ``TypeIs`` mengembalikan ``False``, pemeriksa tipe dapat mempersempit tipe variabel untuk mengecualikan tipe ``TypeIs``.
Typing operator to conceptually mark an object as having been unpacked.
Operator typing untuk menandai sebuah objek secara konseptual sebagai telah di-unpack.
For example, using the unpack operator ``*`` on a :ref:`type variable tuple <typevartuple>` is equivalent to using ``Unpack`` to mark the type variable tuple as having been unpacked::
Sebagai contoh, menggunakan operator unpack ``*`` pada sebuah :ref:`tuple variabel tipe <typevartuple>` sama dengan menggunakan ``Unpack`` untuk menandai tuple variabel tipe sebagai telah di-unpack::
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]
# Effectively does:
tup: tuple[Unpack[Ts]]
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]
# Effectively does:
tup: tuple[Unpack[Ts]]
In fact, ``Unpack`` can be used interchangeably with ``*`` in the context of :class:`typing.TypeVarTuple <TypeVarTuple>` and :class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used explicitly in older versions of Python, where ``*`` couldn't be used in certain places::
Bahkan, ``Unpack`` dapat digunakan secara bergantian dengan ``*`` dalam konteks tipe :class:`typing.TypeVarTuple <TypeVarTuple>` dan :class:`builtins.tuple <tuple>`. Anda mungkin melihat ``Unpack`` digunakan secara eksplisit dalam versi Python yang lebih lama, ketika ``*`` tidak dapat digunakan di tempat-tempat tertentu::
# In older versions of Python, TypeVarTuple and Unpack
# are located in the `typing_extensions` backports package.
from typing_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts] # Syntax error on Python <= 3.10!
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
# In older versions of Python, TypeVarTuple and Unpack
# are located in the `typing_extensions` backports package.
from typing_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple('Ts')
tup: tuple[*Ts] # Syntax error on Python <= 3.10!
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
``Unpack`` can also be used along with :class:`typing.TypedDict` for typing ``**kwargs`` in a function signature::
``Unpack`` juga dapat digunakan bersama :class:`typing.TypedDict` untuk menganotasi ``**kwargs`` dalam sebuah signatur fungsi::
from typing import TypedDict, Unpack
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - `name` of type `str`
# and `year` of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
from typing import TypedDict, Unpack
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - `name` of type `str`
# and `year` of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing.
Lihat :pep:`692` untuk detail selengkapnya tentang penggunaan ``Unpack`` untuk penipean ``**kwargs``.
Building generic types and type aliases
Membangun tipe generik dan alias tipe
The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.
Kelas-kelas berikut tidak boleh digunakan langsung sebagai anotasi. Tujuan penggunaannya adalah sebagai blok pembangun untuk membuat tipe generik dan alias tipe.
These objects can be created through special syntax (:ref:`type parameter lists <type-params>` and the :keyword:`type` statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.
Objek-objek ini dapat dibuat melalui sintaks khusus (:ref:`daftar parameter tipe <type-params>` dan pernyataan :keyword:`type`). Untuk kompatibilitas dengan Python 3.11 dan yang lebih lama, objek-objek ini juga dapat dibuat tanpa sintaks khusus tersebut, sebagaimana didokumentasikan di bawah ini.
Abstract base class for generic types.
Kelas dasar abstrak untuk tipe generik.
A generic type is typically declared by adding a list of type parameters after the class name::
Sebuah tipe generik biasanya dideklarasikan dengan menambahkan sebuah daftar parameter tipe setelah nama kelas::
class Mapping[KT, VT]:
def __getitem__(self, key: KT) -> VT:
...
# Etc.
class Mapping[KT, VT]:
def __getitem__(self, key: KT) -> VT:
...
# Etc.
Such a class implicitly inherits from ``Generic``. The runtime semantics of this syntax are discussed in the :ref:`Language Reference <generic-classes>`.
Kelas semacam itu secara implisit mewarisi dari ``Generic``. Semantik runtime dari sintaks ini dibahas dalam :ref:`Language Reference <generic-classes>`.
This class can then be used as follows::
Kelas ini kemudian dapat digunakan sebagai berikut::
def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
try:
return mapping[key]
except KeyError:
return default
def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
try:
return mapping[key]
except KeyError:
return default
Here the brackets after the function name indicate a :ref:`generic function <generic-functions>`.
Di sini tanda kurung siku setelah nama fungsi menunjukkan sebuah :ref:`fungsi generik <generic-functions>`.
For backwards compatibility, generic classes can also be declared by explicitly inheriting from ``Generic``. In this case, the type parameters must be declared separately::
Untuk kompatibilitas mundur, kelas generik juga dapat dideklarasikan dengan mewarisi secara eksplisit dari ``Generic``. Dalam kasus ini, parameter tipe harus dideklarasikan secara terpisah::
KT = TypeVar('KT')
VT = TypeVar('VT')
class Mapping(Generic[KT, VT]):
def __getitem__(self, key: KT) -> VT:
...
# Etc.
KT = TypeVar('KT')
VT = TypeVar('VT')
class Mapping(Generic[KT, VT]):
def __getitem__(self, key: KT) -> VT:
...
# Etc.
Type variable.
Variabel tipe.
The preferred way to construct a type variable is via the dedicated syntax for :ref:`generic functions <generic-functions>`, :ref:`generic classes <generic-classes>`, and :ref:`generic type aliases <generic-type-aliases>`::
Cara yang lebih disukai untuk membangun sebuah variabel tipe adalah melalui sintaks khusus untuk :ref:`fungsi generik <generic-functions>`, :ref:`kelas generik <generic-classes>`, dan :ref:`alias tipe generik <generic-type-aliases>`::
class Sequence[T]: # T is a TypeVar
...
class Sequence[T]: # T is a TypeVar
...
This syntax can also be used to create bounded and constrained type variables::
Sintaks ini juga dapat digunakan untuk membuat variabel tipe yang dibatasi dan terkekang::
class StrSequence[S: str]: # S is a TypeVar with a `str` upper bound;
... # we can say that S is "bounded by `str`"
class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to str or bytes
...
class StrSequence[S: str]: # S is a TypeVar with a `str` upper bound;
... # we can say that S is "bounded by `str`"
class StrOrBytesSequence[A: (str, bytes)]: # A is a TypeVar constrained to str or bytes
...
However, if desired, reusable type variables can also be constructed manually, like so::
Namun, jika diinginkan, variabel tipe yang dapat digunakan kembali juga dapat dibangun secara manual, seperti berikut::
T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytes
T = TypeVar('T') # Can be anything
S = TypeVar('S', bound=str) # Can be any subtype of str
A = TypeVar('A', str, bytes) # Must be exactly str or bytes
Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See :class:`Generic` for more information on generic types. Generic functions work as follows::
Variabel tipe ada terutama untuk kepentingan pemeriksa tipe statis. Variabel tipe berfungsi sebagai parameter untuk tipe generik serta untuk definisi fungsi generik dan alias tipe. Lihat :class:`Generic` untuk informasi lebih lanjut tentang tipe generik. Fungsi generik bekerja sebagai berikut::
def repeat[T](x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def print_capitalized[S: str](x: S) -> S:
"""Print x capitalized, and return x."""
print(x.capitalize())
return x
def concatenate[A: (str, bytes)](x: A, y: A) -> A:
"""Add two strings or bytes objects together."""
return x + y
def repeat[T](x: T, n: int) -> Sequence[T]:
"""Return a list containing n references to x."""
return [x]*n
def print_capitalized[S: str](x: S) -> S:
"""Print x capitalized, and return x."""
print(x.capitalize())
return x
def concatenate[A: (str, bytes)](x: A, y: A) -> A:
"""Add two strings or bytes objects together."""
return x + y
Note that type variables can be *bounded*, *constrained*, or neither, but cannot be both bounded *and* constrained.
Perlu diperhatikan bahwa variabel tipe dapat *dibatasi*, *terkekang*, atau tidak keduanya, tetapi tidak dapat sekaligus dibatasi *dan* terkekang.
The variance of type variables is inferred by type checkers when they are created through the :ref:`type parameter syntax <type-params>` or when ``infer_variance=True`` is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing ``covariant=True`` or ``contravariant=True``. By default, manually created type variables are invariant. See :pep:`484` and :pep:`695` for more details.
Varians variabel tipe disimpulkan oleh pemeriksa tipe ketika variabel tipe dibuat melalui :ref:`sintaks parameter tipe <type-params>` atau ketika ``infer_variance=True`` diteruskan. Variabel tipe yang dibuat secara manual dapat ditandai secara eksplisit sebagai kovarian atau kontravarian dengan meneruskan ``covariant=True`` atau ``contravariant=True``. Secara default, variabel tipe yang dibuat secara manual bersifat invarian. Lihat :pep:`484` dan :pep:`695` untuk detail selengkapnya.
Bounded type variables and constrained type variables have different semantics in several important ways. Using a *bounded* type variable means that the ``TypeVar`` will be solved using the most specific type possible::
Variabel tipe yang dibatasi dan variabel tipe yang terkekang memiliki semantik yang berbeda dalam beberapa hal penting. Menggunakan variabel tipe yang *dibatasi* berarti ``TypeVar`` akan dipecahkan menggunakan tipe yang paling spesifik::
x = print_capitalized('a string')
reveal_type(x) # revealed type is str
class StringSubclass(str):
pass
y = print_capitalized(StringSubclass('another string'))
reveal_type(y) # revealed type is StringSubclass
z = print_capitalized(45) # error: int is not a subtype of str
x = print_capitalized('a string')
reveal_type(x) # revealed type is str
class StringSubclass(str):
pass
y = print_capitalized(StringSubclass('another string'))
reveal_type(y) # revealed type is StringSubclass
z = print_capitalized(45) # error: int is not a subtype of str
The upper bound of a type variable can be a concrete type, abstract type (ABC or Protocol), or even a union of types::
Batas atas dari sebuah variabel tipe dapat berupa sebuah tipe konkret, tipe abstrak (ABC atau Protocol), atau bahkan sebuah gabungan tipe::
# Can be anything with an __abs__ method
def print_abs[T: SupportsAbs](arg: T) -> None:
print("Absolute value:", abs(arg))
U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method
# Can be anything with an __abs__ method
def print_abs[T: SupportsAbs](arg: T) -> None:
print("Absolute value:", abs(arg))
U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method
Using a *constrained* type variable, however, means that the ``TypeVar`` can only ever be solved as being exactly one of the constraints given::
Menggunakan variabel tipe yang *terkekang*, sebaliknya, berarti ``TypeVar`` hanya dapat dipecahkan sebagai tepat salah satu dari batasan yang diberikan::
a = concatenate('one', 'two')
reveal_type(a) # revealed type is str
b = concatenate(StringSubclass('one'), StringSubclass('two'))
reveal_type(b) # revealed type is str, despite StringSubclass being passed in
c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both
a = concatenate('one', 'two')
reveal_type(a) # revealed type is str
b = concatenate(StringSubclass('one'), StringSubclass('two'))
reveal_type(b) # revealed type is str, despite StringSubclass being passed in
c = concatenate('one', b'two') # error: type variable 'A' can be either str or bytes in a function call, but not both
At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`.
Pada runtime, ``isinstance(x, T)`` akan memunculkan :exc:`TypeError`.
The name of the type variable.
Nama dari variabel tipe.
Whether the type var has been explicitly marked as covariant.
Apakah variabel tipe telah ditandai secara eksplisit sebagai kovarian.
Whether the type var has been explicitly marked as contravariant.
Apakah variabel tipe telah ditandai secara eksplisit sebagai kontravarian.
Whether the type variable's variance should be inferred by type checkers.
Apakah varians variabel tipe harus disimpulkan oleh pemeriksa tipe.
The upper bound of the type variable, if any.
Batas atas dari variabel tipe, jika ada.
For type variables created through :ref:`type parameter syntax <type-params>`, the bound is evaluated only when the attribute is accessed, not when the type variable is created (see :ref:`lazy-evaluation`).
Untuk variabel tipe yang dibuat melalui :ref:`sintaks parameter tipe <type-params>`, batas hanya dievaluasi ketika atribut diakses, bukan ketika variabel tipe dibuat (lihat :ref:`lazy-evaluation`).
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__bound__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`~TypeVar.__bound__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format.
Sebuah :term:`evaluate function` yang berkorespondensi dengan atribut :attr:`~TypeVar.__bound__`. Ketika dipanggil secara langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`~TypeVar.__bound__` secara langsung, tetapi objek metode dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda.
A tuple containing the constraints of the type variable, if any.
Sebuah tuple yang berisi batasan-batasan dari variabel tipe, jika ada.
For type variables created through :ref:`type parameter syntax <type-params>`, the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see :ref:`lazy-evaluation`).
Untuk variabel tipe yang dibuat melalui :ref:`sintaks parameter tipe <type-params>`, batasan-batasan hanya dievaluasi ketika atribut diakses, bukan ketika variabel tipe dibuat (lihat :ref:`lazy-evaluation`).
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__constraints__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`~TypeVar.__constraints__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format.
Sebuah :term:`evaluate function` yang berkorespondensi dengan atribut :attr:`~TypeVar.__constraints__`. Ketika dipanggil secara langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`~TypeVar.__constraints__` secara langsung, tetapi objek metode dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda.
The default value of the type variable, or :data:`typing.NoDefault` if it has no default.
Nilai default dari variabel tipe, atau :data:`typing.NoDefault` jika tidak memiliki default.
An :term:`evaluate function` corresponding to the :attr:`~TypeVar.__default__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`~TypeVar.__default__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format.
Sebuah :term:`evaluate function` yang berkorespondensi dengan atribut :attr:`~TypeVar.__default__`. Ketika dipanggil secara langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`~TypeVar.__default__` secara langsung, tetapi objek metode dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda.
Return whether or not the type variable has a default value. This is equivalent to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` singleton, except that it does not force evaluation of the :ref:`lazily evaluated <lazy-evaluation>` default value.
Mengembalikan apakah variabel tipe memiliki nilai default atau tidak. Hal ini setara dengan memeriksa apakah :attr:`__default__` bukan singleton :data:`typing.NoDefault`, kecuali bahwa pemeriksaan ini tidak memaksa evaluasi dari nilai default yang dievaluasi secara :ref:`tunda <lazy-evaluation>`.
Type variables can now be declared using the :ref:`type parameter <type-params>` syntax introduced by :pep:`695`. The ``infer_variance`` parameter was added.
Variabel tipe kini dapat dideklarasikan menggunakan sintaks :ref:`parameter tipe <type-params>` yang diperkenalkan oleh :pep:`695`. Parameter ``infer_variance`` ditambahkan.
Support for default values was added.
Dukungan untuk nilai default ditambahkan.
Type variable tuple. A specialized form of :ref:`type variable <typevar>` that enables *variadic* generics.
Tuple variabel tipe. Sebuah bentuk khusus dari :ref:`variabel tipe <typevar>` yang memungkinkan generik *variadik*.
Type variable tuples can be declared in :ref:`type parameter lists <type-params>` using a single asterisk (``*``) before the name::
Tuple variabel tipe dapat dideklarasikan dalam :ref:`daftar parameter tipe <type-params>` menggunakan satu asterisk (``*``) sebelum nama::
def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
return (*tup[1:], tup[0])
def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
return (*tup[1:], tup[0])
Or by explicitly invoking the ``TypeVarTuple`` constructor::
Atau dengan memanggil konstruktor ``TypeVarTuple`` secara eksplisit::
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
return (*tup[1:], tup[0])
T = TypeVar("T")
Ts = TypeVarTuple("Ts")
def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
return (*tup[1:], tup[0])
A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an *arbitrary* number of types by acting like an *arbitrary* number of type variables wrapped in a tuple. For example::
Sebuah variabel tipe normal memungkinkan parameterisasi dengan satu tipe. Sebaliknya, sebuah tuple variabel tipe memungkinkan parameterisasi dengan jumlah tipe yang *sembarang* dengan bertindak seperti sejumlah *sembarang* variabel tipe yang dibungkus dalam sebuah tuple. Sebagai contoh::
# T is bound to int, Ts is bound to ()
# Return value is (1,), which has type tuple[int]
move_first_element_to_last(tup=(1,))
# T is bound to int, Ts is bound to (str,)
# Return value is ('spam', 1), which has type tuple[str, int]
move_first_element_to_last(tup=(1, 'spam'))
# T is bound to int, Ts is bound to (str, float)
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
move_first_element_to_last(tup=(1, 'spam', 3.0))
# This fails to type check (and fails at runtime)
# because tuple[()] is not compatible with tuple[T, *Ts]
# (at least one element is required)
move_first_element_to_last(tup=())
# T is bound to int, Ts is bound to ()
# Return value is (1,), which has type tuple[int]
move_first_element_to_last(tup=(1,))
# T is bound to int, Ts is bound to (str,)
# Return value is ('spam', 1), which has type tuple[str, int]
move_first_element_to_last(tup=(1, 'spam'))
# T is bound to int, Ts is bound to (str, float)
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
move_first_element_to_last(tup=(1, 'spam', 3.0))
# This fails to type check (and fails at runtime)
# because tuple[()] is not compatible with tuple[T, *Ts]
# (at least one element is required)
move_first_element_to_last(tup=())
Note the use of the unpacking operator ``*`` in ``tuple[T, *Ts]``. Conceptually, you can think of ``Ts`` as a tuple of type variables ``(T1, T2, ...)``. ``tuple[T, *Ts]`` would then become ``tuple[T, *(T1, T2, ...)]``, which is equivalent to ``tuple[T, T1, T2, ...]``. (Note that in older versions of Python, you might see this written using :data:`Unpack <Unpack>` instead, as ``Unpack[Ts]``.)
Perhatikan penggunaan operator unpacking ``*`` dalam ``tuple[T, *Ts]``. Secara konseptual, Anda dapat menganggap ``Ts`` sebagai sebuah tuple dari variabel tipe ``(T1, T2, ...)``. ``tuple[T, *Ts]`` kemudian akan menjadi ``tuple[T, *(T1, T2, ...)]``, yang setara dengan ``tuple[T, T1, T2, ...]``. (Perlu diperhatikan bahwa dalam versi Python yang lebih lama, Anda mungkin melihat hal ini ditulis menggunakan :data:`Unpack <Unpack>` sebagai gantinya, sebagai ``Unpack[Ts]``.)
Type variable tuples must *always* be unpacked. This helps distinguish type variable tuples from normal type variables::
Tuple variabel tipe *selalu* harus di-unpack. Hal ini membantu membedakan tuple variabel tipe dari variabel tipe normal::
x: Ts # Not valid
x: tuple[Ts] # Not valid
x: tuple[*Ts] # The correct way to do it
x: Ts # Not valid
x: tuple[Ts] # Not valid
x: tuple[*Ts] # The correct way to do it
Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types::
Tuple variabel tipe dapat digunakan dalam konteks yang sama seperti variabel tipe normal. Sebagai contoh, dalam definisi kelas, argumen, dan tipe kembalian::
class Array[*Shape]:
def __getitem__(self, key: tuple[*Shape]) -> float: ...
def __abs__(self) -> "Array[*Shape]": ...
def get_shape(self) -> tuple[*Shape]: ...
class Array[*Shape]:
def __getitem__(self, key: tuple[*Shape]) -> float: ...
def __abs__(self) -> "Array[*Shape]": ...
def get_shape(self) -> tuple[*Shape]: ...
Type variable tuples can be happily combined with normal type variables:
Tuple variabel tipe dapat dikombinasikan dengan mudah dengan variabel tipe normal:
class Array[DType, *Shape]: # This is fine
pass
class Array2[*Shape, DType]: # This would also be fine
pass
class Height: ...
class Width: ...
float_array_1d: Array[float, Height] = Array() # Totally fine
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
class Array[DType, *Shape]: # This is fine
pass
class Array2[*Shape, DType]: # This would also be fine
pass
class Height: ...
class Width: ...
float_array_1d: Array[float, Height] = Array() # Totally fine
int_array_2d: Array[int, Height, Width] = Array() # Yup, fine too
However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters::
Namun, perlu diperhatikan bahwa paling banyak satu tuple variabel tipe dapat muncul dalam satu daftar argumen tipe atau parameter tipe::
x: tuple[*Ts, *Ts] # Not valid
class Array[*Shape, *Shape]: # Not valid
pass
x: tuple[*Ts, *Ts] # Not valid
class Array[*Shape, *Shape]: # Not valid
pass
Finally, an unpacked type variable tuple can be used as the type annotation of ``*args``::
Terakhir, sebuah tuple variabel tipe yang telah di-unpack dapat digunakan sebagai anotasi tipe dari ``*args``::
def call_soon[*Ts](
callback: Callable[[*Ts], None],
*args: *Ts
) -> None:
...
callback(*args)
def call_soon[*Ts](
callback: Callable[[*Ts], None],
*args: *Ts
) -> None:
...
callback(*args)
In contrast to non-unpacked annotations of ``*args`` - e.g. ``*args: int``, which would specify that *all* arguments are ``int`` - ``*args: *Ts`` enables reference to the types of the *individual* arguments in ``*args``. Here, this allows us to ensure the types of the ``*args`` passed to ``call_soon`` match the types of the (positional) arguments of ``callback``.
Berbeda dengan anotasi ``*args`` yang tidak di-unpack - misalnya ``*args: int``, yang menetapkan bahwa *semua* argumen adalah ``int`` - ``*args: *Ts`` memungkinkan merujuk ke tipe dari argumen-argumen *individual* dalam ``*args``. Di sini, hal ini memungkinkan kita memastikan tipe-tipe dari ``*args`` yang diteruskan ke ``call_soon`` cocok dengan tipe-tipe dari argumen (posisional) ``callback``.
See :pep:`646` for more details on type variable tuples.
Lihat :pep:`646` untuk detail selengkapnya tentang tuple variabel tipe.
The name of the type variable tuple.
Nama dari tuple variabel tipe.
Whether the type variable tuple has been explicitly marked as covariant.
Apakah tuple variabel tipe telah ditandai secara eksplisit sebagai kovarian.
Whether the type variable tuple has been explicitly marked as contravariant.
Apakah tuple variabel tipe telah ditandai secara eksplisit sebagai kontravarian.
Whether the type variable tuple's variance should be inferred by type checkers.
Apakah varians tuple variabel tipe harus disimpulkan oleh pemeriksa tipe.
The default value of the type variable tuple, or :data:`typing.NoDefault` if it has no default.
Nilai default dari tuple variabel tipe, atau :data:`typing.NoDefault` jika tidak memiliki default.
An :term:`evaluate function` corresponding to the :attr:`~TypeVarTuple.__default__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`~TypeVarTuple.__default__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format.
Sebuah :term:`evaluate function` yang berkorespondensi dengan atribut :attr:`~TypeVarTuple.__default__`. Ketika dipanggil secara langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`~TypeVarTuple.__default__` secara langsung, tetapi objek metode dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda.
Return whether or not the type variable tuple has a default value. This is equivalent to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` singleton, except that it does not force evaluation of the :ref:`lazily evaluated <lazy-evaluation>` default value.
Mengembalikan apakah tuple variabel tipe memiliki nilai default atau tidak. Hal ini setara dengan memeriksa apakah :attr:`__default__` bukan singleton :data:`typing.NoDefault`, kecuali bahwa pemeriksaan ini tidak memaksa evaluasi dari nilai default yang dievaluasi secara :ref:`tunda <lazy-evaluation>`.
Type variable tuples created with ``covariant=True`` or ``contravariant=True`` can be used to declare covariant or contravariant generic types. The ``bound`` argument is also accepted, similar to :class:`TypeVar`, but its actual semantics are yet to be decided.
Tuple variabel tipe yang dibuat dengan ``covariant=True`` atau ``contravariant=True`` dapat digunakan untuk mendeklarasikan tipe generik yang kovarian atau kontravarian. Argumen ``bound`` juga diterima, mirip dengan :class:`TypeVar`, tetapi semantik sebenarnya belum diputuskan.
Type variable tuples can now be declared using the :ref:`type parameter <type-params>` syntax introduced by :pep:`695`.
Tuple variabel tipe kini dapat dideklarasikan menggunakan sintaks :ref:`parameter tipe <type-params>` yang diperkenalkan oleh :pep:`695`.
Added support for the ``bound``, ``covariant``, ``contravariant``, and ``infer_variance`` parameters.
Dukungan untuk parameter ``bound``, ``covariant``, ``contravariant``, dan ``infer_variance`` ditambahkan.
Parameter specification variable. A specialized version of :ref:`type variables <typevar>`.
Variabel spesifikasi parameter. Sebuah versi khusus dari :ref:`variabel tipe <typevar>`.
In :ref:`type parameter lists <type-params>`, parameter specifications can be declared with two asterisks (``**``)::
Dalam :ref:`daftar parameter tipe <type-params>`, spesifikasi parameter dapat dideklarasikan dengan dua asterisk (``**``)::
type IntFunc[**P] = Callable[P, int]
type IntFunc[**P] = Callable[P, int]
For compatibility with Python 3.11 and earlier, ``ParamSpec`` objects can also be created as follows::
Untuk kompatibilitas dengan Python 3.11 dan yang lebih lama, objek ``ParamSpec`` juga dapat dibuat sebagai berikut::
P = ParamSpec('P')
P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable -- a pattern commonly found in higher order functions and decorators. They are only valid when used in ``Concatenate``, or as the first argument to ``Callable``, or as parameters for user-defined Generics. See :class:`Generic` for more information on generic types.
Variabel spesifikasi parameter ada terutama untuk kepentingan pemeriksa tipe statis. Variabel ini digunakan untuk meneruskan tipe parameter dari satu callable ke callable lain -- sebuah pola yang umum ditemukan dalam fungsi orde tinggi dan dekorator. Variabel ini hanya valid ketika digunakan dalam ``Concatenate``, atau sebagai argumen pertama untuk ``Callable``, atau sebagai parameter untuk Generics yang didefinisikan pengguna. Lihat :class:`Generic` untuk informasi lebih lanjut tentang tipe generik.
For example, to add basic logging to a function, one can create a decorator ``add_logging`` to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters::
Sebagai contoh, untuk menambahkan logging dasar ke sebuah fungsi, seseorang dapat membuat sebuah dekorator ``add_logging`` untuk mencatat pemanggilan fungsi. Variabel spesifikasi parameter memberi tahu pemeriksa tipe bahwa callable yang diteruskan ke dekorator dan callable baru yang dikembalikan olehnya memiliki parameter tipe yang saling bergantung::
from collections.abc import Callable
import logging
def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
from collections.abc import Callable
import logging
def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Without ``ParamSpec``, the simplest way to annotate this previously was to use a :class:`TypeVar` with upper bound ``Callable[..., Any]``. However this causes two problems:
Tanpa ``ParamSpec``, cara paling sederhana untuk menganotasi hal ini sebelumnya adalah menggunakan :class:`TypeVar` dengan batas atas ``Callable[..., Any]``. Namun hal ini menimbulkan dua masalah:
The type checker can't type check the ``inner`` function because ``*args`` and ``**kwargs`` have to be typed :data:`Any`.
Pemeriksa tipe tidak dapat memeriksa tipe fungsi ``inner`` karena ``*args`` dan ``**kwargs`` harus diberi tipe :data:`Any`.
:func:`~cast` may be required in the body of the ``add_logging`` decorator when returning the ``inner`` function, or the static type checker must be told to ignore the ``return inner``.
:func:`~cast` mungkin diperlukan dalam badan dekorator ``add_logging`` saat mengembalikan fungsi ``inner``, atau pemeriksa tipe statis harus diberi tahu untuk mengabaikan ``return inner``.
Since ``ParamSpec`` captures both positional and keyword parameters, ``P.args`` and ``P.kwargs`` can be used to split a ``ParamSpec`` into its components. ``P.args`` represents the tuple of positional parameters in a given call and should only be used to annotate ``*args``. ``P.kwargs`` represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate ``**kwargs``. Both attributes require the annotated parameter to be in scope. At runtime, ``P.args`` and ``P.kwargs`` are instances respectively of :class:`ParamSpecArgs` and :class:`ParamSpecKwargs`.
Karena ``ParamSpec`` menangkap parameter posisional maupun keyword, ``P.args`` dan ``P.kwargs`` dapat digunakan untuk memecah sebuah ``ParamSpec`` menjadi komponen-komponennya. ``P.args`` merepresentasikan tuple parameter posisional dalam sebuah pemanggilan dan hanya boleh digunakan untuk menganotasi ``*args``. ``P.kwargs`` merepresentasikan pemetaan parameter keyword ke nilai-nilainya dalam sebuah pemanggilan, dan hanya boleh digunakan untuk menganotasi ``**kwargs``. Kedua atribut mengharuskan parameter yang dianotasi berada dalam cakupan. Pada runtime, ``P.args`` dan ``P.kwargs`` masing-masing adalah instance dari :class:`ParamSpecArgs` dan :class:`ParamSpecKwargs`.
The name of the parameter specification.
Nama dari spesifikasi parameter.
Whether the parameter specification has been explicitly marked as covariant.
Apakah spesifikasi parameter telah ditandai secara eksplisit sebagai kovarian.
Whether the parameter specification has been explicitly marked as contravariant.
Apakah spesifikasi parameter telah ditandai secara eksplisit sebagai kontravarian.
Whether the parameter specification's variance should be inferred by type checkers.
Apakah varians spesifikasi parameter harus disimpulkan oleh pemeriksa tipe.
The default value of the parameter specification, or :data:`typing.NoDefault` if it has no default.
Nilai default dari spesifikasi parameter, atau :data:`typing.NoDefault` jika tidak memiliki default.
An :term:`evaluate function` corresponding to the :attr:`~ParamSpec.__default__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`~ParamSpec.__default__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format.
Sebuah :term:`evaluate function` yang berkorespondensi dengan atribut :attr:`~ParamSpec.__default__`. Ketika dipanggil secara langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`~ParamSpec.__default__` secara langsung, tetapi objek metode dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda.
Return whether or not the parameter specification has a default value. This is equivalent to checking whether :attr:`__default__` is not the :data:`typing.NoDefault` singleton, except that it does not force evaluation of the :ref:`lazily evaluated <lazy-evaluation>` default value.
Mengembalikan apakah spesifikasi parameter memiliki nilai default atau tidak. Hal ini setara dengan memeriksa apakah :attr:`__default__` bukan singleton :data:`typing.NoDefault`, kecuali bahwa pemeriksaan ini tidak memaksa evaluasi dari nilai default yang dievaluasi secara :ref:`tunda <lazy-evaluation>`.
Parameter specification variables created with ``covariant=True`` or ``contravariant=True`` can be used to declare covariant or contravariant generic types. The ``bound`` argument is also accepted, similar to :class:`TypeVar`. However the actual semantics of these keywords are yet to be decided.
Variabel spesifikasi parameter yang dibuat dengan ``covariant=True`` atau ``contravariant=True`` dapat digunakan untuk mendeklarasikan tipe generik kovarian atau kontravarian. Argumen ``bound`` juga diterima, mirip dengan :class:`TypeVar`. Namun, semantik sebenarnya dari kata kunci ini masih belum diputuskan.
Parameter specifications can now be declared using the :ref:`type parameter <type-params>` syntax introduced by :pep:`695`.
Spesifikasi parameter kini dapat dideklarasikan menggunakan sintaks :ref:`parameter tipe <type-params>` yang diperkenalkan oleh :pep:`695`.
Only parameter specification variables defined in global scope can be pickled.
Hanya variabel spesifikasi parameter yang didefinisikan dalam lingkup global yang dapat di-pickle.
:data:`Concatenate`
:data:`Concatenate`
Arguments and keyword arguments attributes of a :class:`ParamSpec`. The ``P.args`` attribute of a ``ParamSpec`` is an instance of ``ParamSpecArgs``, and ``P.kwargs`` is an instance of ``ParamSpecKwargs``. They are intended for runtime introspection and have no special meaning to static type checkers.
Atribut argumen dan argumen kata kunci dari sebuah :class:`ParamSpec`. Atribut ``P.args`` dari sebuah ``ParamSpec`` adalah instance dari ``ParamSpecArgs``, dan ``P.kwargs`` adalah instance dari ``ParamSpecKwargs``. Keduanya dimaksudkan untuk introspeksi runtime dan tidak memiliki makna khusus bagi pemeriksa tipe statis.
Calling :func:`get_origin` on either of these objects will return the original ``ParamSpec``:
Memanggil :func:`get_origin` pada salah satu objek ini akan mengembalikan ``ParamSpec`` aslinya:
>>> from typing import ParamSpec, get_origin
>>> P = ParamSpec("P")
>>> get_origin(P.args) is P
True
>>> get_origin(P.kwargs) is P
True
>>> from typing import ParamSpec, get_origin
>>> P = ParamSpec("P")
>>> get_origin(P.args) is P
True
>>> get_origin(P.kwargs) is P
True
The type of type aliases created through the :keyword:`type` statement.
Tipe dari alias tipe yang dibuat melalui pernyataan :keyword:`type`.
>>> type Alias = int
>>> type(Alias)
<class 'typing.TypeAliasType'>
>>> type Alias = int
>>> type(Alias)
<class 'typing.TypeAliasType'>
The name of the type alias:
Nama dari alias tipe:
>>> type Alias = int
>>> Alias.__name__
'Alias'
>>> type Alias = int
>>> Alias.__name__
'Alias'
The :term:`qualified name` of the type alias:
:term:`qualified name` dari alias tipe:
>>> class Class:
... type Alias = int
...
>>> Class.Alias.__qualname__
'Class.Alias'
>>> class Class:
... type Alias = int
...
>>> Class.Alias.__qualname__
'Class.Alias'
The name of the module in which the type alias was defined::
Nama modul tempat alias tipe didefinisikan::
>>> type Alias = int
>>> Alias.__module__
'__main__'
>>> type Alias = int
>>> Alias.__module__
'__main__'
This attribute is writable.
Atribut ini dapat ditulis.
The attribute is now writable.
Atribut ini kini dapat ditulis.
The type parameters of the type alias, or an empty tuple if the alias is not generic:
Parameter tipe dari alias tipe, atau tuple kosong jika alias tersebut tidak generik:
>>> type ListOrSet[T] = list[T] | set[T]
>>> ListOrSet.__type_params__
(T,)
>>> type NotGeneric = int
>>> NotGeneric.__type_params__
()
>>> type ListOrSet[T] = list[T] | set[T]
>>> ListOrSet.__type_params__
(T,)
>>> type NotGeneric = int
>>> NotGeneric.__type_params__
()
The type alias's value. This is :ref:`lazily evaluated <lazy-evaluation>`, so names used in the definition of the alias are not resolved until the ``__value__`` attribute is accessed:
Nilai alias tipe. Nilai ini dievaluasi secara :ref:`tunda <lazy-evaluation>`, sehingga nama-nama yang digunakan dalam definisi alias tidak diselesaikan hingga atribut ``__value__`` diakses:
>>> type Mutually = Recursive
>>> type Recursive = Mutually
>>> Mutually
Mutually
>>> Recursive
Recursive
>>> Mutually.__value__
Recursive
>>> Recursive.__value__
Mutually
>>> type Mutually = Recursive
>>> type Recursive = Mutually
>>> Mutually
Mutually
>>> Recursive
Recursive
>>> Mutually.__value__
Recursive
>>> Recursive.__value__
Mutually
An :term:`evaluate function` corresponding to the :attr:`__value__` attribute. When called directly, this method supports only the :attr:`~annotationlib.Format.VALUE` format, which is equivalent to accessing the :attr:`__value__` attribute directly, but the method object can be passed to :func:`annotationlib.call_evaluate_function` to evaluate the value in a different format:
Sebuah :term:`evaluate function` yang bersesuaian dengan atribut :attr:`__value__`. Saat dipanggil langsung, metode ini hanya mendukung format :attr:`~annotationlib.Format.VALUE`, yang setara dengan mengakses atribut :attr:`__value__` secara langsung, tetapi objek metode ini dapat diteruskan ke :func:`annotationlib.call_evaluate_function` untuk mengevaluasi nilai dalam format yang berbeda:
>>> type Alias = undefined
>>> Alias.__value__
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> from annotationlib import Format, call_evaluate_function
>>> Alias.evaluate_value(Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
ForwardRef('undefined')
>>> type Alias = undefined
>>> Alias.__value__
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> from annotationlib import Format, call_evaluate_function
>>> Alias.evaluate_value(Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
ForwardRef('undefined')
Unpacking
Unpacking
Type aliases support star unpacking using the ``*Alias`` syntax. This is equivalent to using ``Unpack[Alias]`` directly:
Alias tipe mendukung star unpacking menggunakan sintaks ``*Alias``. Hal ini setara dengan menggunakan ``Unpack[Alias]`` secara langsung:
>>> type Alias = tuple[int, str]
>>> type Unpacked = tuple[bool, *Alias]
>>> Unpacked.__value__
tuple[bool, typing.Unpack[Alias]]
>>> type Alias = tuple[int, str]
>>> type Unpacked = tuple[bool, *Alias]
>>> Unpacked.__value__
tuple[bool, typing.Unpack[Alias]]
Other special directives
Direktif khusus lainnya
These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.
Fungsi dan kelas ini tidak boleh digunakan secara langsung sebagai anotasi. Tujuan penggunaannya adalah sebagai blok pembangun untuk membuat dan mendeklarasikan tipe.
Typed version of :func:`collections.namedtuple`.
Versi bertipe dari :func:`collections.namedtuple`.
Usage::
Penggunaan::
class Employee(NamedTuple):
name: str
id: int
class Employee(NamedTuple):
name: str
id: int
This is equivalent to::
Ini setara dengan::
Employee = collections.namedtuple('Employee', ['name', 'id'])
Employee = collections.namedtuple('Employee', ['name', 'id'])
To give a field a default value, you can assign to it in the class body::
Untuk memberi sebuah field nilai default, Anda dapat menetapkannya di dalam badan kelas::
class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3
class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3
Fields with a default value must come after any fields without a default.
Field dengan nilai default harus diletakkan setelah field mana pun yang tidak memiliki nilai default.
The types for each field name can be retrieved by calling :func:`annotationlib.get_annotations` on the resulting class. (The field names are in the ``_fields`` attribute and the default values are in the ``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple` API.)
Tipe untuk setiap nama field dapat diambil dengan memanggil :func:`annotationlib.get_annotations` pada kelas hasil. (Nama-nama field terdapat dalam atribut ``_fields`` dan nilai-nilai default terdapat dalam atribut ``_field_defaults``, yang keduanya merupakan bagian dari API :func:`~collections.namedtuple`.)
``NamedTuple`` subclasses can also have docstrings and methods::
Subkelas ``NamedTuple`` juga dapat memiliki docstring dan metode::
class Employee(NamedTuple):
"""Represents an employee."""
name: str
id: int = 3
def __repr__(self) -> str:
return f'<Employee {self.name}, id={self.id}>'
class Employee(NamedTuple):
"""Represents an employee."""
name: str
id: int = 3
def __repr__(self) -> str:
return f'<Employee {self.name}, id={self.id}>'
``NamedTuple`` subclasses can be generic::
Subkelas ``NamedTuple`` juga dapat bersifat generik::
class Group[T](NamedTuple):
key: T
group: list[T]
class Group[T](NamedTuple):
key: T
group: list[T]
Backward-compatible usage::
Penggunaan yang kompatibel dengan versi lama::
# For creating a generic NamedTuple on Python 3.11
T = TypeVar("T")
class Group(NamedTuple, Generic[T]):
key: T
group: list[T]
# A functional syntax is also supported
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
# For creating a generic NamedTuple on Python 3.11
T = TypeVar("T")
class Group(NamedTuple, Generic[T]):
key: T
group: list[T]
# A functional syntax is also supported
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
Added support for :pep:`526` variable annotation syntax.
Ditambahkan dukungan untuk sintaks anotasi variabel :pep:`526`.
Added support for default values, methods, and docstrings.
Ditambahkan dukungan untuk nilai default, metode, dan docstring.
The ``_field_types`` and ``__annotations__`` attributes are now regular dictionaries instead of instances of ``OrderedDict``.
Atribut ``_field_types`` dan ``__annotations__`` kini berupa dictionary biasa, bukan instance dari ``OrderedDict``.
Removed the ``_field_types`` attribute in favor of the more standard ``__annotations__`` attribute which has the same information.
Atribut ``_field_types`` dihapus dan digantikan oleh atribut ``__annotations__`` yang lebih standar, yang memuat informasi yang sama.
``NamedTuple`` is now a function rather than a class. It can still be used as a class base, as described above.
``NamedTuple`` kini merupakan sebuah fungsi, bukan sebuah kelas. Ia tetap dapat digunakan sebagai kelas dasar, sebagaimana dijelaskan di atas.
Added support for generic namedtuples.
Ditambahkan dukungan untuk namedtuple generik.
Using :func:`super` (and the ``__class__`` :term:`closure variable`) in methods of ``NamedTuple`` subclasses is unsupported and causes a :class:`TypeError`.
Menggunakan :func:`super` (dan :term:`closure variable` ``__class__``) dalam metode subkelas ``NamedTuple`` tidak didukung dan menyebabkan :class:`TypeError`.
Helper class to create low-overhead :ref:`distinct types <distinct>`.
Kelas pembantu untuk membuat :ref:`tipe berbeda <distinct>` dengan overhead rendah.
A ``NewType`` is considered a distinct type by a type checker. At runtime, however, calling a ``NewType`` returns its argument unchanged.
Sebuah ``NewType`` dianggap sebagai tipe yang berbeda oleh pemeriksa tipe. Namun, pada saat runtime, memanggil sebuah ``NewType`` akan mengembalikan argumennya tanpa perubahan.
UserId = NewType('UserId', int) # Declare the NewType "UserId"
first_user = UserId(1) # "UserId" returns the argument unchanged at runtime
UserId = NewType('UserId', int) # Declare the NewType "UserId"
first_user = UserId(1) # "UserId" returns the argument unchanged at runtime
The name of the module in which the new type is defined.
Nama modul tempat tipe baru didefinisikan.
The name of the new type.
Nama dari tipe baru.
The type that the new type is based on.
Tipe yang menjadi dasar bagi tipe baru.
``NewType`` is now a class rather than a function.
``NewType`` kini merupakan sebuah kelas, bukan sebuah fungsi.
Base class for protocol classes.
Kelas dasar untuk kelas protokol.
Protocol classes are defined like this::
Kelas protokol didefinisikan seperti ini::
class Proto(Protocol):
def meth(self) -> int:
...
class Proto(Protocol):
def meth(self) -> int:
...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example::
Kelas-kelas seperti ini terutama digunakan bersama pemeriksa tipe statis yang mengenali subtyping struktural (duck-typing statis), misalnya::
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
class C:
def meth(self) -> int:
return 0
def func(x: Proto) -> int:
return x.meth()
func(C()) # Passes static type check
See :pep:`544` for more details. Protocol classes decorated with :deco:`runtime_checkable` (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes without this decorator cannot be used as the second argument to :func:`isinstance` or :func:`issubclass`.
Lihat :pep:`544` untuk detail lebih lanjut. Kelas protokol yang didekorasi dengan :deco:`runtime_checkable` (dijelaskan kemudian) bertindak sebagai protokol runtime sederhana yang hanya memeriksa keberadaan atribut tertentu, dengan mengabaikan signatur tipenya. Kelas protokol tanpa dekorator ini tidak dapat digunakan sebagai argumen kedua untuk :func:`isinstance` atau :func:`issubclass`.
Protocol classes can be generic, for example::
Kelas protokol dapat bersifat generik, misalnya::
class GenProto[T](Protocol):
def meth(self) -> T:
...
class GenProto[T](Protocol):
def meth(self) -> T:
...
In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows::
Dalam kode yang harus kompatibel dengan Python 3.11 atau yang lebih lama, Protokol generik dapat ditulis sebagai berikut::
T = TypeVar("T")
class GenProto(Protocol[T]):
def meth(self) -> T:
...
T = TypeVar("T")
class GenProto(Protocol[T]):
def meth(self) -> T:
...
It is deprecated to call :func:`isinstance` and :func:`issubclass` checks on protocol classes that were not explicitly decorated with :func:`!runtime_checkable` but that inherit from a runtime-checkable protocol class. This will throw a :exc:`TypeError` in Python 3.20.
Memanggil pemeriksaan :func:`isinstance` dan :func:`issubclass` pada kelas protokol yang tidak didekorasi secara eksplisit dengan :func:`!runtime_checkable` tetapi mewarisi dari kelas protokol yang runtime-checkable sudah tidak disarankan lagi. Hal ini akan memunculkan :exc:`TypeError` pada Python 3.20.
Mark a protocol class as a runtime protocol.
Menandai sebuah kelas protokol sebagai protokol runtime.
Such a protocol can be used with :func:`isinstance` and :func:`issubclass`. This allows a simple-minded structural check, very similar to "one-trick ponies" in :mod:`collections.abc` such as :class:`~collections.abc.Iterable`. For example::
Protokol seperti ini dapat digunakan bersama :func:`isinstance` dan :func:`issubclass`. Hal ini memungkinkan pemeriksaan struktural sederhana, yang sangat mirip dengan "one-trick ponies" dalam :mod:`collections.abc` seperti :class:`~collections.abc.Iterable`. Misalnya::
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
@runtime_checkable
class Named(Protocol):
name: str
import threading
assert isinstance(threading.Thread(name='Bob'), Named)
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
@runtime_checkable
class Named(Protocol):
name: str
import threading
assert isinstance(threading.Thread(name='Bob'), Named)
Runtime checkability of protocols is not inherited. A subclass of a runtime-checkable protocol is only runtime-checkable if it is explicitly marked as such, regardless of class hierarchy::
Kemampuan untuk diperiksa saat runtime pada protokol tidak diwariskan. Subkelas dari sebuah protokol yang runtime-checkable hanya bersifat runtime-checkable jika ditandai secara eksplisit, terlepas dari hierarki kelas::
@runtime_checkable
class Iterable(Protocol):
def __iter__(self): ...
# Without @runtime_checkable, Reversible would no longer be runtime-checkable.
@runtime_checkable
class Reversible(Iterable, Protocol):
def __reversed__(self): ...
@runtime_checkable
class Iterable(Protocol):
def __iter__(self): ...
# Without @runtime_checkable, Reversible would no longer be runtime-checkable.
@runtime_checkable
class Reversible(Iterable, Protocol):
def __reversed__(self): ...
This decorator raises :exc:`TypeError` when applied to a non-protocol class.
Dekorator ini memunculkan :exc:`TypeError` saat diterapkan pada kelas nonprotokol.
:deco:`!runtime_checkable` will check only the presence of the required methods or attributes, not their type signatures or types. For example, :class:`ssl.SSLObject` is a class, therefore it passes an :func:`issubclass` check against :ref:`Callable <annotating-callables>`. However, the ``ssl.SSLObject.__init__`` method exists only to raise a :exc:`TypeError` with a more informative message, therefore making it impossible to call (instantiate) :class:`ssl.SSLObject`.
:deco:`!runtime_checkable` hanya akan memeriksa keberadaan metode atau atribut yang diperlukan, bukan signatur tipe atau tipenya. Misalnya, :class:`ssl.SSLObject` adalah sebuah kelas, sehingga ia lolos pemeriksaan :func:`issubclass` terhadap :ref:`Callable <annotating-callables>`. Namun, metode ``ssl.SSLObject.__init__`` hanya ada untuk memunculkan :exc:`TypeError` dengan pesan yang lebih informatif, sehingga :class:`ssl.SSLObject` tidak mungkin dipanggil (diinstansiasi).
An :func:`isinstance` check against a runtime-checkable protocol can be surprisingly slow compared to an ``isinstance()`` check against a non-protocol class. Consider using alternative idioms such as :func:`hasattr` calls for structural checks in performance-sensitive code.
Pemeriksaan :func:`isinstance` terhadap sebuah protokol yang runtime-checkable dapat menjadi sangat lambat dibandingkan dengan pemeriksaan ``isinstance()`` terhadap kelas nonprotokol. Pertimbangkan untuk menggunakan idiom alternatif seperti pemanggilan :func:`hasattr` untuk pemeriksaan struktural dalam kode yang sensitif terhadap kinerja.
The internal implementation of :func:`isinstance` checks against runtime-checkable protocols now uses :func:`inspect.getattr_static` to look up attributes (previously, :func:`hasattr` was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.
Implementasi internal pemeriksaan :func:`isinstance` terhadap protokol yang runtime-checkable kini menggunakan :func:`inspect.getattr_static` untuk mencari atribut (sebelumnya, :func:`hasattr` digunakan). Akibatnya, beberapa objek yang sebelumnya dianggap sebagai instance dari sebuah protokol yang runtime-checkable mungkin tidak lagi dianggap sebagai instance dari protokol tersebut pada Python 3.12+, dan sebaliknya. Sebagian besar pengguna kemungkinan tidak akan terpengaruh oleh perubahan ini.
The members of a runtime-checkable protocol are now considered "frozen" at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on :func:`isinstance` checks comparing objects to the protocol. See :ref:`What's new in Python 3.12 <whatsnew-typing-py312>` for more details.
Anggota-anggota dari sebuah protokol yang runtime-checkable kini dianggap "frozen" pada saat runtime segera setelah kelas dibuat. Melakukan monkey-patching atribut ke sebuah protokol yang runtime-checkable tetap akan berfungsi, tetapi tidak akan berpengaruh pada pemeriksaan :func:`isinstance` yang membandingkan objek dengan protokol tersebut. Lihat :ref:`Apa yang baru di Python 3.12 <whatsnew-typing-py312>` untuk detail lebih lanjut.
Special construct to add type hints to a dictionary. At runtime ":class:`!TypedDict` instances" are simply :class:`dicts <dict>`.
Konstruk khusus untuk menambahkan petunjuk tipe ke sebuah dictionary. Pada saat runtime, instance-instance :class:`!TypedDict` hanyalah :class:`dicts <dict>`.
``TypedDict`` declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage::
``TypedDict`` mendeklarasikan sebuah tipe dictionary yang mengharapkan semua instance-nya memiliki sekumpulan kunci tertentu, dengan setiap kunci dikaitkan dengan nilai yang tipenya konsisten. Harapan ini tidak diperiksa pada saat runtime, melainkan hanya ditegakkan oleh pemeriksa tipe. Penggunaan::
class Point2D(TypedDict):
x: int
y: int
label: str
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
class Point2D(TypedDict):
x: int
y: int
label: str
a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
An alternative way to create a ``TypedDict`` is by using function-call syntax. The second argument must be a literal :class:`dict`::
Cara alternatif untuk membuat ``TypedDict`` adalah dengan menggunakan sintaks pemanggilan fungsi. Argumen kedua harus berupa :class:`dict` literal::
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
This functional syntax allows defining keys which are not valid :ref:`identifiers <identifiers>`, for example because they are keywords or contain hyphens, or when key names must not be :ref:`mangled <private-name-mangling>` like regular private names::
Sintaks fungsional ini memungkinkan pendefinisian kunci-kunci yang bukan merupakan :ref:`identifier <identifiers>` yang valid, misalnya karena merupakan kata kunci atau mengandung tanda hubung, atau ketika nama kunci tidak boleh mengalami :ref:`name mangling <private-name-mangling>` seperti nama privat biasa::
# raises SyntaxError
class Point2D(TypedDict):
in: int # 'in' is a keyword
x-y: int # name with hyphens
class Definition(TypedDict):
__schema: str # mangled to `_Definition__schema`
# OK, functional syntax
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
Definition = TypedDict('Definition', {'__schema': str}) # not mangled
# raises SyntaxError
class Point2D(TypedDict):
in: int # 'in' is a keyword
x-y: int # name with hyphens
class Definition(TypedDict):
__schema: str # mangled to `_Definition__schema`
# OK, functional syntax
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
Definition = TypedDict('Definition', {'__schema': str}) # not mangled
By default, all keys must be present in a ``TypedDict``. It is possible to mark individual keys as non-required using :data:`NotRequired`::
Secara default, semua kunci harus ada dalam sebuah ``TypedDict``. Dimungkinkan untuk menandai kunci individual sebagai tidak wajib menggunakan :data:`NotRequired`::
class Point2D(TypedDict):
x: int
y: int
label: NotRequired[str]
# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})
class Point2D(TypedDict):
x: int
y: int
label: NotRequired[str]
# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})
This means that a ``Point2D`` ``TypedDict`` can have the ``label`` key omitted.
Ini berarti bahwa sebuah ``TypedDict`` ``Point2D`` dapat tidak memiliki kunci ``label``.
It is also possible to mark all keys as non-required by default by specifying a totality of ``False``::
Dimungkinkan juga untuk menandai semua kunci sebagai tidak wajib secara default dengan menetapkan totalitas ``False``::
class Point2D(TypedDict, total=False):
x: int
y: int
# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)
class Point2D(TypedDict, total=False):
x: int
y: int
# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)
This means that a ``Point2D`` ``TypedDict`` can have any of the keys omitted. A type checker is only expected to support a literal ``False`` or ``True`` as the value of the ``total`` argument. ``True`` is the default, and makes all items defined in the class body required.
Ini berarti bahwa sebuah ``TypedDict`` ``Point2D`` dapat tidak memiliki kunci apa pun. Pemeriksa tipe hanya diharapkan mendukung literal ``False`` atau ``True`` sebagai nilai argumen ``total``. ``True`` adalah nilai default, dan membuat semua item yang didefinisikan dalam badan kelas menjadi wajib.
Individual keys of a ``total=False`` ``TypedDict`` can be marked as required using :data:`Required`::
Kunci individual dari sebuah ``TypedDict`` dengan ``total=False`` dapat ditandai sebagai wajib menggunakan :data:`Required`::
class Point2D(TypedDict, total=False):
x: Required[int]
y: Required[int]
label: str
# Alternative syntax
Point2D = TypedDict('Point2D', {
'x': Required[int],
'y': Required[int],
'label': str
}, total=False)
class Point2D(TypedDict, total=False):
x: Required[int]
y: Required[int]
label: str
# Alternative syntax
Point2D = TypedDict('Point2D', {
'x': Required[int],
'y': Required[int],
'label': str
}, total=False)
It is possible for a ``TypedDict`` type to inherit from one or more other ``TypedDict`` types using the class-based syntax. Usage::
Dimungkinkan bagi sebuah tipe ``TypedDict`` untuk mewarisi dari satu atau lebih tipe ``TypedDict`` lainnya menggunakan sintaks berbasis kelas. Penggunaan::
class Point3D(Point2D):
z: int
class Point3D(Point2D):
z: int
``Point3D`` has three items: ``x``, ``y`` and ``z``. It is equivalent to this definition::
``Point3D`` memiliki tiga item: ``x``, ``y`` dan ``z``. Hal ini setara dengan definisi berikut::
class Point3D(TypedDict):
x: int
y: int
z: int
class Point3D(TypedDict):
x: int
y: int
z: int
By default, a ``TypedDict`` is open, meaning that it may contain additional keys at runtime beyond those defined in the class body. The *closed* class argument can be used to control this; if ``closed=True``, the ``TypedDict`` cannot contain additional keys.
Secara default, sebuah ``TypedDict`` bersifat terbuka, yang berarti ia dapat memuat kunci tambahan pada saat runtime di luar yang didefinisikan dalam badan kelas. Argumen kelas *closed* dapat digunakan untuk mengontrol hal ini; jika ``closed=True``, ``TypedDict`` tidak dapat memuat kunci tambahan.
class ClosedPoint(TypedDict, closed=True):
x: int
y: int
class ClosedPoint3D(ClosedPoint): # type checker error: cannot add keys to a closed TypedDict
z: int
class ClosedPoint(TypedDict, closed=True):
x: int
y: int
class ClosedPoint3D(ClosedPoint): # type checker error: cannot add keys to a closed TypedDict
z: int
Setting ``closed=False`` explicitly requests the default open behavior. If the argument is not passed, this state is inherited from the parent class.
Menetapkan ``closed=False`` secara eksplisit meminta perilaku terbuka yang merupakan default. Jika argumen tidak diteruskan, keadaan ini diwarisi dari kelas induk.
In addition to being open or closed, a ``TypedDict`` can also be configured to have extra items. If the *extra_items* class argument is set to a type, the ``TypedDict`` can contain arbitrary additional keys, but the values of those keys must be of the specified type.
Selain bersifat terbuka atau tertutup, sebuah ``TypedDict`` juga dapat dikonfigurasi untuk memiliki item tambahan. Jika argumen kelas *extra_items* ditetapkan ke sebuah tipe, ``TypedDict`` dapat memuat kunci tambahan apa pun, tetapi nilai dari kunci-kunci tersebut harus bertipe sesuai dengan tipe yang ditetapkan.
class ExtraItemsPoint(TypedDict, extra_items=int):
x: int
y: int
point: ExtraItemsPoint = {'x': 1, 'y': 2, 'anything': 3} # OK
class ExtraItemsPoint(TypedDict, extra_items=int):
x: int
y: int
point: ExtraItemsPoint = {'x': 1, 'y': 2, 'anything': 3} # OK
The *extra_items* argument is also inherited through subclassing. It is unset by default, and it may not be used together with the *closed* argument.
Argumen *extra_items* juga diwarisi melalui pembuatan subkelas. Argumen ini tidak ditetapkan secara default, dan tidak boleh digunakan bersama dengan argumen *closed*.
A ``TypedDict`` cannot inherit from a non-\ ``TypedDict`` class, except for :class:`Generic`. For example::
Sebuah ``TypedDict`` tidak dapat mewarisi dari kelas non- ``TypedDict``, kecuali :class:`Generic`. Misalnya::
class X(TypedDict):
x: int
class Y(TypedDict):
y: int
class Z(object): pass # A non-TypedDict class
class XY(X, Y): pass # OK
class XZ(X, Z): pass # raises TypeError
class X(TypedDict):
x: int
class Y(TypedDict):
y: int
class Z(object): pass # A non-TypedDict class
class XY(X, Y): pass # OK
class XZ(X, Z): pass # raises TypeError
A ``TypedDict`` can be generic::
Sebuah ``TypedDict`` dapat bersifat generik::
class Group[T](TypedDict):
key: T
group: list[T]
class Group[T](TypedDict):
key: T
group: list[T]
To create a generic ``TypedDict`` that is compatible with Python 3.11 or lower, inherit from :class:`Generic` explicitly:
Untuk membuat ``TypedDict`` generik yang kompatibel dengan Python 3.11 atau yang lebih rendah, warisi dari :class:`Generic` secara eksplisit:
T = TypeVar("T")
class Group(TypedDict, Generic[T]):
key: T
group: list[T]
T = TypeVar("T")
class Group(TypedDict, Generic[T]):
key: T
group: list[T]
A ``TypedDict`` can be introspected via :func:`annotationlib.get_annotations` (see :ref:`annotations-howto` for more information on annotations best practices) and the following attributes:
Sebuah ``TypedDict`` dapat diintrospeksi melalui :func:`annotationlib.get_annotations` (lihat :ref:`annotations-howto` untuk informasi lebih lanjut tentang praktik terbaik anotasi) dan atribut-atribut berikut:
``Point2D.__total__`` gives the value of the ``total`` argument. Example:
``Point2D.__total__`` memberikan nilai dari argumen ``total``. Contoh:
>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True
>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True
This attribute reflects *only* the value of the ``total`` argument to the current ``TypedDict`` class, not whether the class is semantically total. For example, a ``TypedDict`` with ``__total__`` set to ``True`` may have keys marked with :data:`NotRequired`, or it may inherit from another ``TypedDict`` with ``total=False``. Therefore, it is generally better to use :attr:`__required_keys__` and :attr:`__optional_keys__` for introspection.
Atribut ini hanya mencerminkan nilai dari argumen ``total`` pada kelas ``TypedDict`` saat ini, bukan apakah kelas tersebut secara semantik bersifat total. Misalnya, sebuah ``TypedDict`` dengan ``__total__`` yang ditetapkan ke ``True`` dapat memiliki kunci yang ditandai dengan :data:`NotRequired`, atau dapat mewarisi dari ``TypedDict`` lain dengan ``total=False``. Oleh karena itu, umumnya lebih baik menggunakan :attr:`__required_keys__` dan :attr:`__optional_keys__` untuk introspeksi.
``Point2D.__required_keys__`` and ``Point2D.__optional_keys__`` return :class:`frozenset` objects containing required and non-required keys, respectively.
``Point2D.__required_keys__`` dan ``Point2D.__optional_keys__`` mengembalikan objek :class:`frozenset` yang masing-masing berisi kunci wajib dan kunci tidak wajib.
Keys marked with :data:`Required` will always appear in ``__required_keys__`` and keys marked with :data:`NotRequired` will always appear in ``__optional_keys__``.
Kunci yang ditandai dengan :data:`Required` akan selalu muncul dalam ``__required_keys__`` dan kunci yang ditandai dengan :data:`NotRequired` akan selalu muncul dalam ``__optional_keys__``.
For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same ``TypedDict``. This is done by declaring a ``TypedDict`` with one value for the ``total`` argument and then inheriting from it in another ``TypedDict`` with a different value for ``total``:
Untuk kompatibilitas ke belakang dengan Python 3.10 ke bawah, dimungkinkan juga untuk menggunakan pewarisan guna mendeklarasikan kunci wajib dan kunci tidak wajib dalam ``TypedDict`` yang sama. Hal ini dilakukan dengan mendeklarasikan sebuah ``TypedDict`` dengan satu nilai untuk argumen ``total`` lalu mewarisinya dalam ``TypedDict`` lain dengan nilai ``total`` yang berbeda:
>>> class Point2D(TypedDict, total=False):
... x: int
... y: int
...
>>> class Point3D(Point2D):
... z: int
...
>>> Point3D.__required_keys__ == frozenset({'z'})
True
>>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
True
>>> class Point2D(TypedDict, total=False):
... x: int
... y: int
...
>>> class Point3D(Point2D):
... z: int
...
>>> Point3D.__required_keys__ == frozenset({'z'})
True
>>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
True
If ``from __future__ import annotations`` is used or if annotations are given as strings, annotations are not evaluated when the ``TypedDict`` is defined. Therefore, the runtime introspection that ``__required_keys__`` and ``__optional_keys__`` rely on may not work properly, and the values of the attributes may be incorrect.
Jika ``from __future__ import annotations`` digunakan atau jika anotasi diberikan sebagai string, anotasi tidak dievaluasi ketika ``TypedDict`` didefinisikan. Oleh karena itu, introspeksi runtime yang menjadi dasar ``__required_keys__`` dan ``__optional_keys__`` mungkin tidak berfungsi dengan baik, dan nilai atribut-atribut tersebut mungkin tidak benar.
A :class:`frozenset` containing the names of all read-only keys. Keys are read-only if they carry the :data:`ReadOnly` qualifier.
Sebuah :class:`frozenset` yang memuat nama-nama dari semua kunci yang bersifat hanya-baca. Kunci bersifat hanya-baca jika membawa kualifikasi :data:`ReadOnly`.
A :class:`frozenset` containing the names of all mutable keys. Keys are mutable if they do not carry the :data:`ReadOnly` qualifier.
Sebuah :class:`frozenset` yang memuat nama-nama dari semua kunci yang dapat diubah. Kunci dapat diubah jika tidak membawa kualifikasi :data:`ReadOnly`.
The value of the *closed* class argument. It can be ``True``, ``False``, or :data:`None`.
Nilai dari argumen kelas *closed*. Nilainya dapat berupa ``True``, ``False``, atau :data:`None`.
The value of the *extra_items* class argument. It can be a valid type or :data:`NoExtraItems`.
Nilai dari argumen kelas *extra_items*. Nilainya dapat berupa sebuah tipe yang valid atau :data:`NoExtraItems`.
See the `TypedDict <https://typing.python.org/en/latest/spec/typeddict.html#typeddict>`_ section in the typing documentation for more examples and detailed rules.
Lihat bagian `TypedDict <https://typing.python.org/en/latest/spec/typeddict.html#typeddict>`_ dalam dokumentasi typing untuk contoh-contoh lainnya dan aturan yang lebih rinci.
``TypedDict`` is now a function rather than a class. It can still be used as a class base, as described above.
``TypedDict`` kini merupakan sebuah fungsi, bukan sebuah kelas. Ia tetap dapat digunakan sebagai kelas dasar, sebagaimana dijelaskan di atas.
Added support for marking individual keys as :data:`Required` or :data:`NotRequired`. See :pep:`655`.
Ditambahkan dukungan untuk menandai kunci individual sebagai :data:`Required` atau :data:`NotRequired`. Lihat :pep:`655`.
Added support for generic ``TypedDict``\ s.
Ditambahkan dukungan untuk ``TypedDict`` generik.
Removed support for the keyword-argument method of creating ``TypedDict``\ s.
Dukungan untuk metode argumen kata kunci dalam pembuatan ``TypedDict`` dihapus.
Support for the :data:`ReadOnly` qualifier was added. See :pep:`705`.
Dukungan untuk kualifikasi :data:`ReadOnly` ditambahkan. Lihat :pep:`705`.
Support for the *closed* and *extra_items* class arguments was added. See :pep:`728`.
Dukungan untuk argumen kelas *closed* dan *extra_items* ditambahkan. Lihat :pep:`728`.
Protocols
Protokol
The following protocols are provided by the :mod:`!typing` module. All are decorated with :deco:`runtime_checkable`.
Protokol-protokol berikut disediakan oleh modul :mod:`!typing`. Semuanya didekorasi dengan :deco:`runtime_checkable`.
A protocol with one abstract method ``__abs__`` that is covariant in its return type.
Sebuah protokol dengan satu metode abstrak ``__abs__`` yang kovarian dalam tipe kembaliannya.
A protocol with one abstract method ``__bytes__``.
Sebuah protokol dengan satu metode abstrak ``__bytes__``.
A protocol with one abstract method ``__complex__``.
Sebuah protokol dengan satu metode abstrak ``__complex__``.
A protocol with one abstract method ``__float__``.
Sebuah protokol dengan satu metode abstrak ``__float__``.
A protocol with one abstract method ``__index__``.
Sebuah protokol dengan satu metode abstrak ``__index__``.
A protocol with one abstract method ``__int__``.
Sebuah protokol dengan satu metode abstrak ``__int__``.
A protocol with one abstract method ``__round__`` that is covariant in its return type.
Sebuah protokol dengan satu metode abstrak ``__round__`` yang kovarian dalam tipe kembaliannya.
ABCs and Protocols for working with I/O
ABC dan Protokol untuk bekerja dengan I/O
Generic class ``IO[AnyStr]`` and its subclasses ``TextIO(IO[str])`` and ``BinaryIO(IO[bytes])`` represent the types of I/O streams such as returned by :func:`open`. Please note that these classes are not protocols, and their interface is fairly broad.
Kelas generik ``IO[AnyStr]`` dan subkelas-subkelasnya ``TextIO(IO[str])`` dan ``BinaryIO(IO[bytes])`` merepresentasikan tipe dari aliran I/O seperti yang dikembalikan oleh :func:`open`. Perlu diperhatikan bahwa kelas-kelas ini bukan protokol, dan antarmukanya cukup luas.
The protocols :class:`io.Reader` and :class:`io.Writer` offer a simpler alternative for argument types, when only the ``read()`` or ``write()`` methods are accessed, respectively::
Protokol :class:`io.Reader` dan :class:`io.Writer` menawarkan alternatif yang lebih sederhana untuk tipe argumen, ketika hanya metode ``read()`` atau ``write()`` yang diakses, masing-masing::
def read_and_write(reader: Reader[str], writer: Writer[bytes]):
data = reader.read()
writer.write(data.encode())
def read_and_write(reader: Reader[str], writer: Writer[bytes]):
data = reader.read()
writer.write(data.encode())
Also consider using :class:`collections.abc.Iterable` for iterating over the lines of an input stream::
Pertimbangkan juga untuk menggunakan :class:`collections.abc.Iterable` untuk mengiterasi baris-baris dari sebuah aliran input::
def read_config(stream: Iterable[str]):
for line in stream:
...
def read_config(stream: Iterable[str]):
for line in stream:
...
Functions and decorators
Fungsi dan dekorator
Cast a value to a type.
Melakukan cast suatu nilai ke suatu tipe.
This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don't check anything (we want this to be as fast as possible).
Fungsi ini mengembalikan nilai tanpa perubahan. Bagi pemeriksa tipe, hal ini menandakan bahwa nilai yang dikembalikan memiliki tipe yang ditetapkan, tetapi saat runtime kami sengaja tidak memeriksa apa pun (kami ingin fungsi ini secepat mungkin).
Ask a static type checker to confirm that *val* has an inferred type of *typ*.
Meminta pemeriksa tipe statis untuk mengonfirmasi bahwa *val* memiliki tipe terinferensi *typ*.
At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.
Saat runtime, fungsi ini tidak melakukan apa pun: fungsi ini mengembalikan argumen pertama tanpa perubahan, tanpa pemeriksaan atau efek samping, apa pun tipe aktual dari argumen tersebut.
When a static type checker encounters a call to ``assert_type()``, it emits an error if the value is not of the specified type::
Ketika pemeriksa tipe statis menemukan pemanggilan ``assert_type()``, pemeriksa tersebut memunculkan galat jika nilai tersebut bukan dari tipe yang ditetapkan::
def greet(name: str) -> None:
assert_type(name, str) # OK, inferred type of `name` is `str`
assert_type(name, int) # type checker error
def greet(name: str) -> None:
assert_type(name, str) # OK, inferred type of `name` is `str`
assert_type(name, int) # type checker error
This function is useful for ensuring the type checker's understanding of a script is in line with the developer's intentions::
Fungsi ini berguna untuk memastikan pemahaman pemeriksa tipe terhadap sebuah skrip selaras dengan maksud pengembang::
def complex_function(arg: object):
# Do some complex type-narrowing logic,
# after which we hope the inferred type will be `int`
...
# Test whether the type checker correctly understands our function
assert_type(arg, int)
def complex_function(arg: object):
# Do some complex type-narrowing logic,
# after which we hope the inferred type will be `int`
...
# Test whether the type checker correctly understands our function
assert_type(arg, int)
Ask a static type checker to confirm that a line of code is unreachable.
Meminta pemeriksa tipe statis untuk mengonfirmasi bahwa sebuah baris kode tidak terjangkau.
def int_or_str(arg: int | str) -> None:
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _ as unreachable:
assert_never(unreachable)
def int_or_str(arg: int | str) -> None:
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _ as unreachable:
assert_never(unreachable)
Here, the annotations allow the type checker to infer that the last case can never execute, because ``arg`` is either an :class:`int` or a :class:`str`, and both options are covered by earlier cases.
Di sini, anotasi memungkinkan pemeriksa tipe menyimpulkan bahwa case terakhir tidak akan pernah dieksekusi, karena ``arg`` adalah :class:`int` atau :class:`str`, dan kedua opsi tersebut sudah dicakup oleh case-case sebelumnya.
If a type checker finds that a call to ``assert_never()`` is reachable, it will emit an error. For example, if the type annotation for ``arg`` was instead ``int | str | float``, the type checker would emit an error pointing out that ``unreachable`` is of type :class:`float`. For a call to ``assert_never`` to pass type checking, the inferred type of the argument passed in must be the bottom type, :data:`Never`, and nothing else.
Jika pemeriksa tipe menemukan bahwa pemanggilan ``assert_never()`` dapat terjangkau, pemeriksa tersebut akan memunculkan galat. Misalnya, jika anotasi tipe untuk ``arg`` adalah ``int | str | float``, pemeriksa tipe akan memunculkan galat yang menunjukkan bahwa ``unreachable`` bertipe :class:`float`. Agar pemanggilan ``assert_never`` lolos pemeriksaan tipe, tipe terinferensi dari argumen yang diberikan harus berupa tipe bawah, :data:`Never`, dan tidak ada yang lain.
At runtime, this throws an exception when called.
Saat runtime, fungsi ini melemparkan eksepsi ketika dipanggil.
`Unreachable Code and Exhaustiveness Checking <https://typing.python.org/en/latest/guides/unreachable.html>`__ has more information about exhaustiveness checking with static typing.
`Kode yang Tidak Terjangkau dan Pemeriksaan Kelengkapan <https://typing.python.org/en/latest/guides/unreachable.html>`__ memiliki informasi lebih lanjut tentang pemeriksaan kelengkapan dengan penipean statis.
Ask a static type checker to reveal the inferred type of an expression.
Meminta pemeriksa tipe statis untuk mengungkapkan tipe terinferensi dari sebuah ekspresi.
When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example::
Ketika pemeriksa tipe statis menemukan pemanggilan fungsi ini, pemeriksa tersebut memunculkan diagnostik berisi tipe terinferensi dari argumen tersebut. Misalnya::
x: int = 1
reveal_type(x) # Revealed type is "builtins.int"
x: int = 1
reveal_type(x) # Revealed type is "builtins.int"
This can be useful when you want to debug how your type checker handles a particular piece of code.
Hal ini dapat berguna ketika Anda ingin men-debug cara pemeriksa tipe Anda menangani potongan kode tertentu.
At runtime, this function prints the runtime type of its argument to :data:`sys.stderr` and returns the argument unchanged (allowing the call to be used within an expression)::
Saat runtime, fungsi ini mencetak tipe runtime dari argumennya ke :data:`sys.stderr` dan mengembalikan argumen tanpa perubahan (sehingga pemanggilan tersebut dapat digunakan di dalam sebuah ekspresi)::
x = reveal_type(1) # prints "Runtime type is int"
print(x) # prints "1"
x = reveal_type(1) # prints "Runtime type is int"
print(x) # prints "1"
Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.
Perlu diperhatikan bahwa tipe runtime dapat berbeda dari (lebih atau kurang spesifik daripada) tipe yang diinferensikan secara statis oleh pemeriksa tipe.
Most type checkers support ``reveal_type()`` anywhere, even if the name is not imported from ``typing``. Importing the name from ``typing``, however, allows your code to run without runtime errors and communicates intent more clearly.
Sebagian besar pemeriksa tipe mendukung ``reveal_type()`` di mana pun, meskipun nama tersebut tidak diimpor dari ``typing``. Namun, mengimpor nama tersebut dari ``typing`` memungkinkan kode Anda berjalan tanpa galat runtime dan mengomunikasikan maksud dengan lebih jelas.
Decorator to mark an object as providing :func:`dataclass <dataclasses.dataclass>`-like behavior.
Dekorator untuk menandai sebuah objek sebagai penyedia perilaku mirip :func:`dataclass <dataclasses.dataclass>`.
``@dataclass_transform`` may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of ``@dataclass_transform()`` tells a static type checker that the decorated object performs runtime "magic" that transforms a class in a similar way to :deco:`dataclasses.dataclass`.
``@dataclass_transform`` dapat digunakan untuk mendekorasi sebuah kelas, metaclass, atau fungsi yang juga merupakan dekorator. Kehadiran ``@dataclass_transform()`` memberi tahu pemeriksa tipe statis bahwa objek yang didekorasi melakukan "magic" saat runtime yang mentransformasikan sebuah kelas dengan cara yang mirip dengan :deco:`dataclasses.dataclass`.
Example usage with a decorator function:
Contoh penggunaan dengan fungsi dekorator:
@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
...
return cls
@create_model
class CustomerModel:
id: int
name: str
@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
...
return cls
@create_model
class CustomerModel:
id: int
name: str
On a base class::
Pada kelas dasar::
@dataclass_transform()
class ModelBase: ...
class CustomerModel(ModelBase):
id: int
name: str
@dataclass_transform()
class ModelBase: ...
class CustomerModel(ModelBase):
id: int
name: str
On a metaclass::
Pada metaclass::
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int
name: str
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int
name: str
The ``CustomerModel`` classes defined above will be treated by type checkers similarly to classes created with :deco:`dataclasses.dataclass`. For example, type checkers will assume these classes have ``__init__`` methods that accept ``id`` and ``name``.
Kelas-kelas ``CustomerModel`` yang didefinisikan di atas akan diperlakukan oleh pemeriksa tipe secara mirip dengan kelas yang dibuat dengan :deco:`dataclasses.dataclass`. Misalnya, pemeriksa tipe akan menganggap kelas-kelas ini memiliki metode ``__init__`` yang menerima ``id`` dan ``name``.
The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the :deco:`dataclasses.dataclass` decorator: ``init``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``, ``kw_only``, and ``slots``. It must be possible for the value of these arguments (``True`` or ``False``) to be statically evaluated.
Kelas, metaclass, atau fungsi yang didekorasi dapat menerima argumen bool berikut yang akan dianggap oleh pemeriksa tipe memiliki efek yang sama seperti pada dekorator :deco:`dataclasses.dataclass`: ``init``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, ``match_args``, ``kw_only``, dan ``slots``. Nilai argumen-argumen ini (``True`` atau ``False``) harus dapat dievaluasi secara statis.
The arguments to the ``@dataclass_transform`` decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:
Argumen-argumen pada dekorator ``@dataclass_transform`` dapat digunakan untuk menyesuaikan perilaku default dari kelas, metaclass, atau fungsi yang didekorasi:
Parameters
Parameter
Indicates whether the ``eq`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. Defaults to ``True``.
Menunjukkan apakah parameter ``eq`` diasumsikan bernilai ``True`` atau ``False`` jika dihilangkan oleh pemanggil. Nilai default-nya adalah ``True``.
Indicates whether the ``order`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. Defaults to ``False``.
Menunjukkan apakah parameter ``order`` diasumsikan bernilai ``True`` atau ``False`` jika dihilangkan oleh pemanggil. Nilai default-nya adalah ``False``.
Indicates whether the ``kw_only`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. Defaults to ``False``.
Menunjukkan apakah parameter ``kw_only`` diasumsikan bernilai ``True`` atau ``False`` jika dihilangkan oleh pemanggil. Nilai default-nya adalah ``False``.
Indicates whether the ``frozen`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. Defaults to ``False``. .. versionadded:: 3.12
Menunjukkan apakah parameter ``frozen`` diasumsikan bernilai ``True`` atau ``False`` jika dihilangkan oleh pemanggil. Nilai default-nya adalah ``False``. .. versionadded:: 3.12
Indicates whether the ``frozen`` parameter is assumed to be ``True`` or ``False`` if it is omitted by the caller. Defaults to ``False``.
Menunjukkan apakah parameter ``frozen`` diasumsikan bernilai ``True`` atau ``False`` jika dihilangkan oleh pemanggil. Nilai default-nya adalah ``False``.
Specifies a static list of supported classes or functions that describe fields, similar to :func:`dataclasses.field`. Defaults to ``()``.
Menetapkan daftar statis berisi kelas atau fungsi yang didukung yang mendeskripsikan field, mirip dengan :func:`dataclasses.field`. Nilai default-nya adalah ``()``.
Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.
Argumen kata kunci lain yang sembarang diterima untuk memungkinkan kemungkinan ekstensi di masa mendatang.
Type checkers recognize the following optional parameters on field specifiers:
Pemeriksa tipe mengenali parameter opsional berikut pada penentu field:
**Recognised parameters for field specifiers**
**Parameter yang Dikenali untuk penentu field**
Parameter name
Nama parameter
Description
Deskripsi
``init``
``init``
Indicates whether the field should be included in the synthesized ``__init__`` method. If unspecified, ``init`` defaults to ``True``.
Menunjukkan apakah field harus disertakan dalam metode ``__init__`` yang disintesis. Jika tidak ditetapkan, ``init`` memiliki nilai default ``True``.
``default``
``default``
Provides the default value for the field.
Menyediakan nilai default untuk field.
``default_factory``
``default_factory``
Provides a runtime callback that returns the default value for the field. If neither ``default`` nor ``default_factory`` are specified, the field is assumed to have no default value and must be provided a value when the class is instantiated.
Menyediakan callback runtime yang mengembalikan nilai default untuk field. Jika ``default`` maupun ``default_factory`` tidak ditetapkan, field dianggap tidak memiliki nilai default dan harus diberi nilai ketika kelas diinstansiasi.
``factory``
``factory``
An alias for the ``default_factory`` parameter on field specifiers.
Alias untuk parameter ``default_factory`` pada penentu field.
``kw_only``
``kw_only``
Indicates whether the field should be marked as keyword-only. If ``True``, the field will be keyword-only. If ``False``, it will not be keyword-only. If unspecified, the value of the ``kw_only`` parameter on the object decorated with ``@dataclass_transform`` will be used, or if that is unspecified, the value of ``kw_only_default`` on ``@dataclass_transform`` will be used.
Menunjukkan apakah field harus ditandai sebagai keyword-only. Jika ``True``, field akan menjadi keyword-only. Jika ``False``, field tidak akan menjadi keyword-only. Jika tidak ditetapkan, nilai parameter ``kw_only`` pada objek yang didekorasi dengan ``@dataclass_transform`` akan digunakan, atau jika parameter tersebut juga tidak ditetapkan, nilai ``kw_only_default`` pada ``@dataclass_transform`` akan digunakan.
``alias``
``alias``
Provides an alternative name for the field. This alternative name is used in the synthesized ``__init__`` method.
Menyediakan nama alternatif untuk field. Nama alternatif ini digunakan dalam metode ``__init__`` yang disintesis.
At runtime, this decorator records its arguments in the ``__dataclass_transform__`` attribute on the decorated object. It has no other runtime effect.
Saat runtime, dekorator ini mencatat argumen-argumennya dalam atribut ``__dataclass_transform__`` pada objek yang didekorasi. Dekorator ini tidak memiliki efek runtime lainnya.
See :pep:`681` for more details.
Lihat :pep:`681` untuk detail lebih lanjut.
Decorator for creating overloaded functions and methods.
Dekorator untuk membuat fungsi dan metode yang di-overload.
The ``@overload`` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of ``@overload``-decorated definitions must be followed by exactly one non-``@overload``-decorated definition (for the same function/method).
Dekorator ``@overload`` memungkinkan pendeskripsian fungsi dan metode yang mendukung berbagai kombinasi tipe argumen. Serangkaian definisi yang didekorasi ``@overload`` harus diikuti oleh tepat satu definisi yang tidak didekorasi ``@overload`` (untuk fungsi/metode yang sama).
``@overload``-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-``@overload``-decorated definition. The non-``@overload``-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an ``@overload``-decorated function directly will raise :exc:`NotImplementedError`.
Definisi yang didekorasi ``@overload`` hanya bermanfaat bagi pemeriksa tipe, karena definisi tersebut akan ditimpa oleh definisi yang tidak didekorasi ``@overload``. Sementara itu, definisi yang tidak didekorasi ``@overload`` akan digunakan saat runtime, tetapi harus diabaikan oleh pemeriksa tipe. Saat runtime, memanggil fungsi yang didekorasi ``@overload`` secara langsung akan memunculkan :exc:`NotImplementedError`.
An example of overload that gives a more precise type than can be expressed using a union or a type variable:
Contoh overload yang memberikan tipe yang lebih presisi daripada yang dapat diungkapkan menggunakan union atau variabel tipe:
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
... # actual implementation goes here
@overload
def process(response: None) -> None:
...
@overload
def process(response: int) -> tuple[int, str]:
...
@overload
def process(response: bytes) -> str:
...
def process(response):
... # actual implementation goes here
See :pep:`484` for more details and comparison with other typing semantics.
Lihat :pep:`484` untuk detail lebih lanjut dan perbandingan dengan semantik penipean lainnya.
Overloaded functions can now be introspected at runtime using :func:`get_overloads`.
Fungsi yang di-overload kini dapat diintrospeksi saat runtime menggunakan :func:`get_overloads`.
Return a sequence of :deco:`overload`-decorated definitions for *func*.
Mengembalikan urutan definisi yang didekorasi :deco:`overload` untuk *func*.
*func* is the function object for the implementation of the overloaded function. For example, given the definition of ``process`` in the documentation for :deco:`overload`, ``get_overloads(process)`` will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, ``get_overloads()`` returns an empty sequence.
*func* adalah objek fungsi untuk implementasi dari fungsi yang di-overload. Misalnya, berdasarkan definisi ``process`` dalam dokumentasi untuk :deco:`overload`, ``get_overloads(process)`` akan mengembalikan urutan berisi tiga objek fungsi untuk ketiga overload yang didefinisikan. Jika dipanggil pada fungsi tanpa overload, ``get_overloads()`` mengembalikan urutan kosong.
``get_overloads()`` can be used for introspecting an overloaded function at runtime.
``get_overloads()`` dapat digunakan untuk mengintrospeksi fungsi yang di-overload saat runtime.
Clear all registered overloads in the internal registry.
Menghapus semua overload yang terdaftar dalam registry internal.
This can be used to reclaim the memory used by the registry.
Hal ini dapat digunakan untuk membebaskan kembali memori yang digunakan oleh registry.
Decorator to indicate final methods and final classes.
Dekorator untuk menunjukkan metode final dan kelas final.
Decorating a method with ``@final`` indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with ``@final`` indicates that it cannot be subclassed.
Mendekorasi sebuah metode dengan ``@final`` menunjukkan kepada pemeriksa tipe bahwa metode tersebut tidak dapat di-override dalam subkelas. Mendekorasi sebuah kelas dengan ``@final`` menunjukkan bahwa kelas tersebut tidak dapat dibuat subkelas.
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
The decorator will now attempt to set a ``__final__`` attribute to ``True`` on the decorated object. Thus, a check like ``if getattr(obj, "__final__", False)`` can be used at runtime to determine whether an object ``obj`` has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.
Dekorator ini kini akan mencoba menetapkan atribut ``__final__`` menjadi ``True`` pada objek yang didekorasi. Dengan demikian, pemeriksaan seperti ``if getattr(obj, "__final__", False)`` dapat digunakan saat runtime untuk menentukan apakah sebuah objek ``obj`` telah ditandai sebagai final. Jika objek yang didekorasi tidak mendukung penetapan atribut, dekorator mengembalikan objek tanpa perubahan dan tanpa memunculkan eksepsi.
Decorator to indicate that annotations are not type hints.
Dekorator untuk menunjukkan bahwa anotasi bukan merupakan petunjuk tipe.
This works as a class or function :term:`decorator`. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.
Dekorator ini bekerja sebagai :term:`decorator` kelas atau fungsi. Pada kelas, dekorator ini berlaku secara rekursif pada semua metode dan kelas yang didefinisikan dalam kelas tersebut (tetapi tidak pada metode yang didefinisikan dalam superkelas atau subkelasnya). Pemeriksa tipe akan mengabaikan semua anotasi dalam fungsi atau kelas yang memiliki dekorator ini.
``@no_type_check`` mutates the decorated object in place.
``@no_type_check`` mengubah objek yang didekorasi secara langsung.
Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.
Dekorator untuk menunjukkan bahwa sebuah metode dalam subkelas dimaksudkan untuk meng-override sebuah metode atau atribut dalam superkelas.
Type checkers should emit an error if a method decorated with ``@override`` does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.
Pemeriksa tipe harus memunculkan galat jika metode yang didekorasi dengan ``@override`` ternyata tidak meng-override apa pun. Hal ini membantu mencegah bug yang dapat terjadi ketika kelas dasar diubah tanpa perubahan yang setara pada kelas anak.
class Base:
def log_status(self) -> None:
...
class Sub(Base):
@override
def log_status(self) -> None: # Okay: overrides Base.log_status
...
@override
def done(self) -> None: # Error reported by type checker
...
class Base:
def log_status(self) -> None:
...
class Sub(Base):
@override
def log_status(self) -> None: # Okay: overrides Base.log_status
...
@override
def done(self) -> None: # Error reported by type checker
...
There is no runtime checking of this property.
Tidak ada pemeriksaan runtime atas properti ini.
The decorator will attempt to set an ``__override__`` attribute to ``True`` on the decorated object. Thus, a check like ``if getattr(obj, "__override__", False)`` can be used at runtime to determine whether an object ``obj`` has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.
Dekorator ini akan mencoba menetapkan atribut ``__override__`` menjadi ``True`` pada objek yang didekorasi. Dengan demikian, pemeriksaan seperti ``if getattr(obj, "__override__", False)`` dapat digunakan saat runtime untuk menentukan apakah sebuah objek ``obj`` telah ditandai sebagai override. Jika objek yang didekorasi tidak mendukung penetapan atribut, dekorator mengembalikan objek tanpa perubahan dan tanpa memunculkan eksepsi.
See :pep:`698` for more details.
Lihat :pep:`698` untuk detail lebih lanjut.
Decorator to mark a class as a disjoint base.
Dekorator untuk menandai sebuah kelas sebagai disjoint base.
Type checkers do not allow child classes of a disjoint base ``C`` to inherit from other disjoint bases that are not parent or child classes of ``C``.
Pemeriksa tipe tidak mengizinkan kelas anak dari disjoint base ``C`` mewarisi dari disjoint base lain yang bukan merupakan kelas induk atau kelas anak dari ``C``.
@disjoint_base
class Disjoint1: pass
@disjoint_base
class Disjoint2: pass
class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error
@disjoint_base
class Disjoint1: pass
@disjoint_base
class Disjoint2: pass
class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error
Type checkers can use knowledge of disjoint bases to detect unreachable code and determine when two types can overlap.
Pemeriksa tipe dapat menggunakan pengetahuan tentang disjoint base untuk mendeteksi kode yang tidak terjangkau dan menentukan kapan dua tipe dapat saling tumpang tindih.
The corresponding runtime concept is a solid base (see :ref:`multiple-inheritance`). Classes that are solid bases at runtime can be marked with ``@disjoint_base`` in stub files. Users may also mark other classes as disjoint bases to indicate to type checkers that multiple inheritance with other disjoint bases should not be allowed.
Konsep runtime yang terkait adalah solid base (lihat :ref:`multiple-inheritance`). Kelas-kelas yang merupakan solid base saat runtime dapat ditandai dengan ``@disjoint_base`` dalam berkas stub. Pengguna juga dapat menandai kelas lain sebagai disjoint base untuk menunjukkan kepada pemeriksa tipe bahwa pewarisan berganda dengan disjoint base lain tidak boleh diizinkan.
Note that the concept of a solid base is a CPython implementation detail, and the exact set of standard library classes that are disjoint bases at runtime may change in future versions of Python.
Perlu diperhatikan bahwa konsep solid base adalah detail implementasi CPython, dan kumpulan pasti kelas pustaka standar yang merupakan disjoint base saat runtime dapat berubah pada versi Python mendatang.
Decorator to mark a class or function as unavailable at runtime.
Dekorator untuk menandai sebuah kelas atau fungsi sebagai tidak tersedia saat runtime.
This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class::
Dekorator ini sendiri tidak tersedia saat runtime. Dekorator ini terutama dimaksudkan untuk menandai kelas yang didefinisikan dalam berkas stub tipe jika sebuah implementasi mengembalikan instance dari kelas privat::
@type_check_only
class Response: # private or not available at runtime
code: int
def get_header(self, name: str) -> str: ...
def fetch_response() -> Response: ...
@type_check_only
class Response: # private or not available at runtime
code: int
def get_header(self, name: str) -> str: ...
def fetch_response() -> Response: ...
Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.
Perlu diperhatikan bahwa mengembalikan instance dari kelas privat tidak disarankan. Biasanya lebih baik menjadikan kelas-kelas tersebut publik.
Introspection helpers
Pembantu introspeksi
Return a dictionary containing type hints for a function, method, module, class object, or other callable object.
Mengembalikan dictionary yang berisi petunjuk tipe untuk sebuah fungsi, metode, modul, objek kelas, atau objek callable lainnya.
This is often the same as :func:`annotationlib.get_annotations`, but this function makes the following changes to the annotations dictionary:
Hasilnya sering kali sama dengan :func:`annotationlib.get_annotations`, tetapi fungsi ini membuat perubahan berikut pada dictionary anotasi:
Forward references encoded as string literals or :class:`ForwardRef` objects are handled by evaluating them in *globalns*, *localns*, and (where applicable) *obj*'s :ref:`type parameter <type-params>` namespace. If *globalns* or *localns* is not given, appropriate namespace dictionaries are inferred from *obj*.
Referensi forward yang dikodekan sebagai literal string atau objek :class:`ForwardRef` ditangani dengan mengevaluasinya dalam *globalns*, *localns*, dan (jika berlaku) namespace :ref:`parameter tipe <type-params>` milik *obj*. Jika *globalns* atau *localns* tidak diberikan, dictionary namespace yang sesuai akan diinferensikan dari *obj*.
``None`` is replaced with :class:`types.NoneType`.
``None`` diganti dengan :class:`types.NoneType`.
If :deco:`no_type_check` has been applied to *obj*, an empty dictionary is returned.
Jika :deco:`no_type_check` telah diterapkan pada *obj*, dictionary kosong akan dikembalikan.
If *obj* is a class ``C``, the function returns a dictionary that merges annotations from ``C``'s base classes with those on ``C`` directly. This is done by traversing :attr:`C.__mro__ <type.__mro__>` and iteratively combining :term:`annotations <variable annotation>` of each base class. Annotations on classes appearing earlier in the :term:`method resolution order` always take precedence over annotations on classes appearing later in the method resolution order.
Jika *obj* adalah kelas ``C``, fungsi ini mengembalikan dictionary yang menggabungkan anotasi dari kelas-kelas dasar ``C`` dengan anotasi pada ``C`` secara langsung. Hal ini dilakukan dengan menelusuri :attr:`C.__mro__ <type.__mro__>` dan menggabungkan :term:`annotations <variable annotation>` dari setiap kelas dasar secara berurutan. Anotasi pada kelas yang muncul lebih awal dalam :term:`method resolution order` selalu lebih diutamakan daripada anotasi pada kelas yang muncul lebih akhir dalam method resolution order.
The function recursively replaces all occurrences of ``Annotated[T, ...]``, ``Required[T]``, ``NotRequired[T]``, and ``ReadOnly[T]`` with ``T``, unless *include_extras* is set to ``True`` (see :class:`Annotated` for more information).
Fungsi ini secara rekursif mengganti semua kemunculan ``Annotated[T, ...]``, ``Required[T]``, ``NotRequired[T]``, dan ``ReadOnly[T]`` dengan ``T``, kecuali *include_extras* diatur menjadi ``True`` (lihat :class:`Annotated` untuk informasi lebih lanjut).
This function may execute arbitrary code contained in annotations. See :ref:`annotationlib-security` for more information.
Fungsi ini dapat mengeksekusi kode sembarang yang terdapat dalam anotasi. Lihat :ref:`annotationlib-security` untuk informasi lebih lanjut.
If :attr:`Format.VALUE <annotationlib.Format.VALUE>` is used and any forward references in the annotations of *obj* are not resolvable, a :exc:`NameError` exception is raised. For example, this can happen with names imported under :data:`if TYPE_CHECKING <TYPE_CHECKING>`. More generally, any kind of exception can be raised if an annotation contains invalid Python code.
Jika :attr:`Format.VALUE <annotationlib.Format.VALUE>` digunakan dan ada referensi forward dalam anotasi *obj* yang tidak dapat diselesaikan, eksepsi :exc:`NameError` akan dimunculkan. Misalnya, hal ini dapat terjadi dengan nama yang diimpor di bawah :data:`if TYPE_CHECKING <TYPE_CHECKING>`. Secara lebih umum, segala jenis eksepsi dapat dimunculkan jika sebuah anotasi berisi kode Python yang tidak valid.
Calling :func:`get_type_hints` on an instance is not supported. To retrieve annotations for an instance, call :func:`get_type_hints` on the instance's class instead (for example, ``get_type_hints(type(obj))``).
Memanggil :func:`get_type_hints` pada sebuah instance tidak didukung. Untuk mengambil anotasi dari sebuah instance, panggil :func:`get_type_hints` pada kelas instance tersebut sebagai gantinya (misalnya, ``get_type_hints(type(obj))``).
Added ``include_extras`` parameter as part of :pep:`593`. See the documentation on :data:`Annotated` for more information.
Parameter ``include_extras`` ditambahkan sebagai bagian dari :pep:`593`. Lihat dokumentasi tentang :data:`Annotated` untuk informasi lebih lanjut.
Previously, ``Optional[t]`` was added for function and method annotations if a default value equal to ``None`` was set. Now the annotation is returned unchanged.
Sebelumnya, ``Optional[t]`` ditambahkan untuk anotasi fungsi dan metode jika nilai default yang sama dengan ``None`` ditetapkan. Kini anotasi dikembalikan tanpa perubahan.
Added the ``format`` parameter. See the documentation on :func:`annotationlib.get_annotations` for more information.
Parameter ``format`` ditambahkan. Lihat dokumentasi tentang :func:`annotationlib.get_annotations` untuk informasi lebih lanjut.
Calling :func:`get_type_hints` on instances is no longer supported. Some instances were accepted in earlier versions as an undocumented implementation detail.
Memanggil :func:`get_type_hints` pada instance tidak lagi didukung. Beberapa instance diterima pada versi sebelumnya sebagai detail implementasi yang tidak didokumentasikan.
Get the unsubscripted version of a type: for a typing object of the form ``X[Y, Z, ...]`` return ``X``.
Mendapatkan versi tanpa subskrip dari sebuah tipe: untuk objek typing berbentuk ``X[Y, Z, ...]`` kembalikan ``X``.
If ``X`` is a typing-module alias for a builtin or :mod:`collections` class, it will be normalized to the original class. If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`, return the underlying :class:`ParamSpec`. Return ``None`` for unsupported objects.
Jika ``X`` adalah alias modul typing untuk kelas builtin atau kelas :mod:`collections`, alias tersebut akan dinormalisasi ke kelas aslinya. Jika ``X`` adalah instance dari :class:`ParamSpecArgs` atau :class:`ParamSpecKwargs`, kembalikan :class:`ParamSpec` yang mendasarinya. Kembalikan ``None`` untuk objek yang tidak didukung.
Examples:
Contoh-contoh:
assert get_origin(str) is None
assert get_origin(Dict[str, int]) is dict
assert get_origin(Union[int, str]) is Union
assert get_origin(Annotated[str, "metadata"]) is Annotated
P = ParamSpec('P')
assert get_origin(P.args) is P
assert get_origin(P.kwargs) is P
assert get_origin(str) is None
assert get_origin(Dict[str, int]) is dict
assert get_origin(Union[int, str]) is Union
assert get_origin(Annotated[str, "metadata"]) is Annotated
P = ParamSpec('P')
assert get_origin(P.args) is P
assert get_origin(P.kwargs) is P
Get type arguments with all substitutions performed: for a typing object of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
Mendapatkan argumen tipe dengan semua substitusi yang telah dilakukan: untuk objek typing berbentuk ``X[Y, Z, ...]`` kembalikan ``(Y, Z, ...)``.
If ``X`` is a union or :class:`Literal` contained in another generic type, the order of ``(Y, Z, ...)`` may be different from the order of the original arguments ``[Y, Z, ...]`` due to type caching. Return ``()`` for unsupported objects.
Jika ``X`` adalah union atau :class:`Literal` yang terdapat dalam tipe generik lain, urutan ``(Y, Z, ...)`` dapat berbeda dari urutan argumen asli ``[Y, Z, ...]`` karena caching tipe. Kembalikan ``()`` untuk objek yang tidak didukung.
assert get_args(int) == ()
assert get_args(Dict[int, str]) == (int, str)
assert get_args(Union[int, str]) == (int, str)
assert get_args(int) == ()
assert get_args(Dict[int, str]) == (int, str)
assert get_args(Union[int, str]) == (int, str)
Return the set of members defined in a :class:`Protocol`.
Mengembalikan kumpulan anggota yang didefinisikan dalam sebuah :class:`Protocol`.
>>> from typing import Protocol, get_protocol_members
>>> class P(Protocol):
... def a(self) -> str: ...
... b: int
>>> get_protocol_members(P) == frozenset({'a', 'b'})
True
>>> from typing import Protocol, get_protocol_members
>>> class P(Protocol):
... def a(self) -> str: ...
... b: int
>>> get_protocol_members(P) == frozenset({'a', 'b'})
True
Raise :exc:`TypeError` for arguments that are not Protocols.
Memunculkan :exc:`TypeError` untuk argumen yang bukan Protocol.
Determine if a type is a :class:`Protocol`.
Menentukan apakah sebuah tipe adalah :class:`Protocol`.
class P(Protocol):
def a(self) -> str: ...
b: int
assert is_protocol(P)
assert not is_protocol(int)
class P(Protocol):
def a(self) -> str: ...
b: int
assert is_protocol(P)
assert not is_protocol(int)
This function only returns true for ``Protocol`` classes, not for :ref:`generic aliases <types-genericalias>` of them:
Fungsi ini hanya mengembalikan true untuk kelas ``Protocol``, bukan untuk :ref:`alias generik <types-genericalias>` dari kelas tersebut:
class GenericP[T](Protocol):
def a(self) -> T: ...
b: int
assert not is_protocol(GenericP[int])
class GenericP[T](Protocol):
def a(self) -> T: ...
b: int
assert not is_protocol(GenericP[int])
Check if a type is a :class:`TypedDict`.
Memeriksa apakah sebuah tipe adalah :class:`TypedDict`.
class Film(TypedDict):
title: str
year: int
assert is_typeddict(Film)
assert not is_typeddict(list | str)
# TypedDict is a factory for creating typed dicts,
# not a typed dict itself
assert not is_typeddict(TypedDict)
class Film(TypedDict):
title: str
year: int
assert is_typeddict(Film)
assert not is_typeddict(list | str)
# TypedDict is a factory for creating typed dicts,
# not a typed dict itself
assert not is_typeddict(TypedDict)
This function only returns true for ``TypedDict`` classes, not for :ref:`generic aliases <types-genericalias>` of them:
Fungsi ini hanya mengembalikan true untuk kelas ``TypedDict``, bukan untuk :ref:`alias generik <types-genericalias>` dari kelas tersebut:
class GenericFilm[T](TypedDict):
title: str
year: T
assert not is_typeddict(GenericFilm[int])
class GenericFilm[T](TypedDict):
title: str
year: T
assert not is_typeddict(GenericFilm[int])
Class used for internal typing representation of string forward references.
Kelas yang digunakan untuk representasi penipean internal dari referensi forward berupa string.
For example, ``List["SomeClass"]`` is implicitly transformed into ``List[ForwardRef("SomeClass")]``. :class:`!ForwardRef` should not be instantiated by a user, but may be used by introspection tools.
Misalnya, ``List["SomeClass"]`` secara implisit ditransformasikan menjadi ``List[ForwardRef("SomeClass")]``. :class:`!ForwardRef` sebaiknya tidak diinstansiasi oleh pengguna, tetapi dapat digunakan oleh perkakas introspeksi.
:pep:`585` generic types such as ``list["SomeClass"]`` will not be implicitly transformed into ``list[ForwardRef("SomeClass")]`` and thus will not automatically resolve to ``list[SomeClass]``.
Tipe generik :pep:`585` seperti ``list["SomeClass"]`` tidak akan ditransformasikan secara implisit menjadi ``list[ForwardRef("SomeClass")]`` sehingga tidak akan secara otomatis diselesaikan menjadi ``list[SomeClass]``.
This is now an alias for :class:`annotationlib.ForwardRef`. Several undocumented behaviors of this class have been changed; for example, after a ``ForwardRef`` has been evaluated, the evaluated value is no longer cached.
Kelas ini kini merupakan alias untuk :class:`annotationlib.ForwardRef`. Beberapa perilaku kelas ini yang tidak didokumentasikan telah diubah; misalnya, setelah sebuah ``ForwardRef`` dievaluasi, nilai yang dievaluasi tidak lagi di-cache.
Evaluate an :class:`annotationlib.ForwardRef` as a :term:`type hint`.
Mengevaluasi sebuah :class:`annotationlib.ForwardRef` sebagai :term:`type hint`.
This is similar to calling :meth:`annotationlib.ForwardRef.evaluate`, but unlike that method, :func:`!evaluate_forward_ref` also recursively evaluates forward references nested within the type hint.
Hal ini mirip dengan memanggil :meth:`annotationlib.ForwardRef.evaluate`, tetapi berbeda dengan metode tersebut, :func:`!evaluate_forward_ref` juga mengevaluasi secara rekursif referensi forward yang bersarang di dalam petunjuk tipe.
See the documentation for :meth:`annotationlib.ForwardRef.evaluate` for the meaning of the *owner*, *globals*, *locals*, *type_params*, and *format* parameters.
Lihat dokumentasi untuk :meth:`annotationlib.ForwardRef.evaluate` mengenai arti parameter *owner*, *globals*, *locals*, *type_params*, dan *format*.
A sentinel object used to indicate that a type parameter has no default value. For example:
Objek sentinel yang digunakan untuk menunjukkan bahwa sebuah parameter tipe tidak memiliki nilai default. Misalnya:
>>> T = TypeVar("T")
>>> T.__default__ is typing.NoDefault
True
>>> S = TypeVar("S", default=None)
>>> S.__default__ is None
True
>>> T = TypeVar("T")
>>> T.__default__ is typing.NoDefault
True
>>> S = TypeVar("S", default=None)
>>> S.__default__ is None
True
A :class:`sentinel` object used to indicate that a :class:`TypedDict` does not have the *extra_items* class argument.
Objek :class:`sentinel` yang digunakan untuk menunjukkan bahwa sebuah :class:`TypedDict` tidak memiliki argumen kelas *extra_items*.
>>> from typing import TypedDict, NoExtraItems
>>> class Point(TypedDict):
... x: int
... y: int
...
>>> Point.__extra_items__ is NoExtraItems
True
>>> from typing import TypedDict, NoExtraItems
>>> class Point(TypedDict):
... x: int
... y: int
...
>>> Point.__extra_items__ is NoExtraItems
True
Constant
Konstanta
A special constant that is assumed to be ``True`` by static type checkers. It's ``False`` at runtime.
Konstanta khusus yang diasumsikan bernilai ``True`` oleh pemeriksa tipe statis. Nilainya adalah ``False`` saat runtime.
A module which is expensive to import, and which only contain types used for typing annotations, can be safely imported inside an ``if TYPE_CHECKING:`` block. This prevents the module from actually being imported at runtime; annotations aren't eagerly evaluated (see :pep:`649`) so using undefined symbols in annotations is harmless--as long as you don't later examine them. Your static type analysis tool will set ``TYPE_CHECKING`` to ``True`` during static type analysis, which means the module will be imported and the types will be checked properly during such analysis.
Modul yang mahal untuk diimpor, dan yang hanya berisi tipe yang digunakan untuk anotasi tipe, dapat dengan aman diimpor di dalam blok ``if TYPE_CHECKING:``. Hal ini mencegah modul benar-benar diimpor saat runtime; anotasi tidak dievaluasi secara eager (lihat :pep:`649`) sehingga penggunaan simbol yang tidak terdefinisi dalam anotasi tidak berbahaya--selama Anda tidak memeriksanya nanti. Perkakas analisis tipe statis Anda akan menetapkan ``TYPE_CHECKING`` menjadi ``True`` selama analisis tipe statis, yang berarti modul tersebut akan diimpor dan tipe-tipenya akan diperiksa dengan benar selama analisis tersebut.
if TYPE_CHECKING:
import expensive_mod
def fun(arg: expensive_mod.SomeType) -> None:
local_var: expensive_mod.AnotherType = other_fun()
if TYPE_CHECKING:
import expensive_mod
def fun(arg: expensive_mod.SomeType) -> None:
local_var: expensive_mod.AnotherType = other_fun()
If you occasionally need to examine type annotations at runtime which may contain undefined symbols, use :meth:`annotationlib.get_annotations` with a ``format`` parameter of :attr:`annotationlib.Format.STRING` or :attr:`annotationlib.Format.FORWARDREF` to safely retrieve the annotations without raising :exc:`NameError`.
Jika Anda sesekali perlu memeriksa anotasi tipe saat runtime yang mungkin berisi simbol yang tidak terdefinisi, gunakan :meth:`annotationlib.get_annotations` dengan parameter ``format`` bernilai :attr:`annotationlib.Format.STRING` atau :attr:`annotationlib.Format.FORWARDREF` untuk mengambil anotasi dengan aman tanpa memunculkan :exc:`NameError`.
Deprecated aliases
Alias yang sudah tidak disarankan lagi
This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the :mod:`!typing` module in order to support parameterizing these generic classes using ``[]``. However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support ``[]`` (see :pep:`585`).
Modul ini mendefinisikan beberapa alias yang sudah tidak disarankan lagi untuk kelas-kelas pustaka standar yang sudah ada sebelumnya. Alias-alias ini awalnya disertakan dalam modul :mod:`!typing` untuk mendukung pemberian parameter pada kelas-kelas generik ini menggunakan ``[]``. Namun, alias-alias tersebut menjadi berlebihan di Python 3.9 ketika kelas-kelas yang sudah ada sebelumnya ditingkatkan untuk mendukung ``[]`` (lihat :pep:`585`).
The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.
Tipe-tipe yang berlebihan ini sudah tidak disarankan lagi sejak Python 3.9. Namun, meskipun alias-alias ini mungkin dihapus di suatu saat, penghapusan alias-alias ini saat ini tidak direncanakan. Dengan demikian, saat ini tidak ada peringatan pengusangan yang dikeluarkan oleh interpreter untuk alias-alias ini.
If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the :mod:`!typing` module without deprecation warnings until at least Python 3.14.
Jika di suatu saat diputuskan untuk menghapus alias-alias yang sudah tidak disarankan lagi ini, peringatan pengusangan akan dikeluarkan oleh interpreter setidaknya dua rilis sebelum penghapusan. Alias-alias tersebut dijamin tetap ada dalam modul :mod:`!typing` tanpa peringatan pengusangan hingga setidaknya Python 3.14.
Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.
Pemeriksa tipe didorong untuk menandai penggunaan tipe-tipe yang sudah tidak disarankan lagi jika program yang diperiksa menargetkan versi Python minimum 3.9 atau yang lebih baru.
Aliases to built-in types
Alias untuk tipe bawaan
Deprecated alias to :class:`dict`.
Alias yang sudah tidak disarankan lagi untuk :class:`dict`.
Note that to annotate arguments, it is preferred to use an abstract collection type such as :class:`~collections.abc.Mapping` rather than to use :class:`dict` or :class:`!typing.Dict`.
Perlu diperhatikan bahwa untuk menganotasi argumen, lebih disarankan menggunakan tipe koleksi abstrak seperti :class:`~collections.abc.Mapping` daripada menggunakan :class:`dict` atau :class:`!typing.Dict`.
:class:`builtins.dict <dict>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.dict <dict>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`list`.
Alias yang sudah tidak disarankan lagi untuk :class:`list`.
Note that to annotate arguments, it is preferred to use an abstract collection type such as :class:`~collections.abc.Sequence` or :class:`~collections.abc.Iterable` rather than to use :class:`list` or :class:`!typing.List`.
Perlu diperhatikan bahwa untuk menganotasi argumen, lebih disarankan menggunakan tipe koleksi abstrak seperti :class:`~collections.abc.Sequence` atau :class:`~collections.abc.Iterable` daripada menggunakan :class:`list` atau :class:`!typing.List`.
:class:`builtins.list <list>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.list <list>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`builtins.set <set>`.
Alias yang sudah tidak disarankan lagi untuk :class:`builtins.set <set>`.
Note that to annotate arguments, it is preferred to use an abstract collection type such as :class:`collections.abc.Set` rather than to use :class:`set` or :class:`typing.Set`.
Perlu diperhatikan bahwa untuk menganotasi argumen, lebih disarankan menggunakan tipe koleksi abstrak seperti :class:`collections.abc.Set` daripada menggunakan :class:`set` atau :class:`typing.Set`.
:class:`builtins.set <set>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.set <set>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`builtins.frozenset <frozenset>`.
Alias yang sudah tidak disarankan lagi untuk :class:`builtins.frozenset <frozenset>`.
:class:`builtins.frozenset <frozenset>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.frozenset <frozenset>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias for :class:`tuple`.
Alias yang sudah tidak disarankan lagi untuk :class:`tuple`.
:class:`tuple` and ``Tuple`` are special-cased in the type system; see :ref:`annotating-tuples` for more details.
:class:`tuple` dan ``Tuple`` diperlakukan secara khusus dalam sistem tipe; lihat :ref:`annotating-tuples` untuk detail lebih lanjut.
:class:`builtins.tuple <tuple>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.tuple <tuple>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`type`.
Alias yang sudah tidak disarankan lagi untuk :class:`type`.
See :ref:`type-of-class-objects` for details on using :class:`type` or ``typing.Type`` in type annotations.
Lihat :ref:`type-of-class-objects` untuk detail tentang penggunaan :class:`type` atau ``typing.Type`` dalam anotasi tipe.
:class:`builtins.type <type>` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`builtins.type <type>` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Aliases to types in :mod:`collections`
Alias untuk tipe di :mod:`collections`
Deprecated alias to :class:`collections.defaultdict`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.defaultdict`.
:class:`collections.defaultdict` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.defaultdict` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.OrderedDict`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.OrderedDict`.
:class:`collections.OrderedDict` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.OrderedDict` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.ChainMap`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.ChainMap`.
:class:`collections.ChainMap` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.ChainMap` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.Counter`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.Counter`.
:class:`collections.Counter` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.Counter` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.deque`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.deque`.
:class:`collections.deque` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.deque` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Aliases to other concrete types
Alias untuk tipe konkret lainnya
Deprecated aliases corresponding to the return types from :func:`re.compile` and :func:`re.search`.
Alias yang sudah tidak disarankan lagi yang sesuai dengan tipe kembalian dari :func:`re.compile` dan :func:`re.search`.
These types (and the corresponding functions) are generic over :data:`AnyStr`. ``Pattern`` can be specialised as ``Pattern[str]`` or ``Pattern[bytes]``; ``Match`` can be specialised as ``Match[str]`` or ``Match[bytes]``.
Tipe-tipe ini (dan fungsi-fungsi yang bersesuaian) bersifat generik terhadap :data:`AnyStr`. ``Pattern`` dapat dispesialisasi sebagai ``Pattern[str]`` atau ``Pattern[bytes]``; ``Match`` dapat dispesialisasi sebagai ``Match[str]`` atau ``Match[bytes]``.
Classes ``Pattern`` and ``Match`` from :mod:`re` now support ``[]``. See :pep:`585` and :ref:`types-genericalias`.
Kelas ``Pattern`` dan ``Match`` dari :mod:`re` kini mendukung ``[]``. Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias for :class:`str`.
Alias yang sudah tidak disarankan lagi untuk :class:`str`.
``Text`` is provided to supply a forward compatible path for Python 2 code: in Python 2, ``Text`` is an alias for ``unicode``.
``Text`` disediakan untuk memberikan jalur yang kompatibel ke depan bagi kode Python 2: di Python 2, ``Text`` adalah alias untuk ``unicode``.
Use ``Text`` to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3::
Gunakan ``Text`` untuk menunjukkan bahwa sebuah nilai harus berisi string unicode dengan cara yang kompatibel dengan Python 2 dan Python 3::
def add_unicode_checkmark(text: Text) -> Text:
return text + u' \u2713'
def add_unicode_checkmark(text: Text) -> Text:
return text + u' \u2713'
Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use :class:`str` instead of ``Text``.
Python 2 sudah tidak lagi didukung, dan sebagian besar pemeriksa tipe juga sudah tidak lagi mendukung pemeriksaan tipe kode Python 2. Penghapusan alias ini saat ini tidak direncanakan, tetapi pengguna didorong untuk menggunakan :class:`str` sebagai pengganti ``Text``.
Aliases to container ABCs in :mod:`collections.abc`
Alias untuk ABC kontainer di :mod:`collections.abc`
Deprecated alias to :class:`collections.abc.Set`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Set`.
:class:`collections.abc.Set` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Set` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.ByteString`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.ByteString`.
Use ``isinstance(obj, collections.abc.Buffer)`` to test if ``obj`` implements the :ref:`buffer protocol <bufferobjects>` at runtime. For use in type annotations, either use :class:`~collections.abc.Buffer` or a union that explicitly specifies the types your code supports (e.g., ``bytes | bytearray | memoryview``).
Gunakan ``isinstance(obj, collections.abc.Buffer)`` untuk menguji apakah ``obj`` mengimplementasikan :ref:`buffer protocol <bufferobjects>` saat runtime. Untuk penggunaan dalam anotasi tipe, gunakan :class:`~collections.abc.Buffer` atau sebuah union yang secara eksplisit menentukan tipe-tipe yang didukung oleh kode Anda (misalnya, ``bytes | bytearray | memoryview``).
:class:`!ByteString` was originally intended to be an abstract class that would serve as a supertype of both :class:`bytes` and :class:`bytearray`. However, since the ABC never had any methods, knowing that an object was an instance of :class:`!ByteString` never actually told you anything useful about the object. Other common buffer types such as :class:`memoryview` were also never understood as subtypes of :class:`!ByteString` (either at runtime or by static type checkers).
:class:`!ByteString` awalnya dimaksudkan sebagai kelas abstrak yang akan berfungsi sebagai supertipe dari :class:`bytes` dan :class:`bytearray`. Namun, karena ABC tersebut tidak pernah memiliki metode apa pun, mengetahui bahwa sebuah objek adalah instance dari :class:`!ByteString` sebenarnya tidak pernah memberi tahu Anda apa pun yang berguna tentang objek tersebut. Tipe buffer umum lainnya seperti :class:`memoryview` juga tidak pernah dipahami sebagai subtipe dari :class:`!ByteString` (baik saat runtime maupun oleh pemeriksa tipe statis).
See :pep:`PEP 688 <688#current-options>` for more details.
Lihat :pep:`PEP 688 <688#current-options>` untuk detail lebih lanjut.
Deprecated alias to :class:`collections.abc.Collection`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Collection`.
:class:`collections.abc.Collection` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Collection` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Container`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Container`.
:class:`collections.abc.Container` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Container` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.ItemsView`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.ItemsView`.
:class:`collections.abc.ItemsView` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.ItemsView` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.KeysView`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.KeysView`.
:class:`collections.abc.KeysView` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.KeysView` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Mapping`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Mapping`.
:class:`collections.abc.Mapping` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Mapping` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.MappingView`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.MappingView`.
:class:`collections.abc.MappingView` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.MappingView` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.MutableMapping`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.MutableMapping`.
:class:`collections.abc.MutableMapping` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.MutableMapping` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.MutableSequence`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.MutableSequence`.
:class:`collections.abc.MutableSequence` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.MutableSequence` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.MutableSet`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.MutableSet`.
:class:`collections.abc.MutableSet` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.MutableSet` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Sequence`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Sequence`.
:class:`collections.abc.Sequence` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Sequence` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.ValuesView`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.ValuesView`.
:class:`collections.abc.ValuesView` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.ValuesView` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Aliases to asynchronous ABCs in :mod:`collections.abc`
Alias untuk ABC asinkron di :mod:`collections.abc`
Deprecated alias to :class:`collections.abc.Coroutine`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Coroutine`.
See :ref:`annotating-generators-and-coroutines` for details on using :class:`collections.abc.Coroutine` and ``typing.Coroutine`` in type annotations.
Lihat :ref:`annotating-generators-and-coroutines` untuk detail tentang penggunaan :class:`collections.abc.Coroutine` dan ``typing.Coroutine`` dalam anotasi tipe.
:class:`collections.abc.Coroutine` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Coroutine` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.AsyncGenerator`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.AsyncGenerator`.
See :ref:`annotating-generators-and-coroutines` for details on using :class:`collections.abc.AsyncGenerator` and ``typing.AsyncGenerator`` in type annotations.
Lihat :ref:`annotating-generators-and-coroutines` untuk detail tentang penggunaan :class:`collections.abc.AsyncGenerator` dan ``typing.AsyncGenerator`` dalam anotasi tipe.
:class:`collections.abc.AsyncGenerator` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.AsyncGenerator` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
The ``SendType`` parameter now has a default.
Parameter ``SendType`` kini memiliki nilai default.
Deprecated alias to :class:`collections.abc.AsyncIterable`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.AsyncIterable`.
:class:`collections.abc.AsyncIterable` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.AsyncIterable` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.AsyncIterator`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.AsyncIterator`.
:class:`collections.abc.AsyncIterator` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.AsyncIterator` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Awaitable`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Awaitable`.
:class:`collections.abc.Awaitable` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Awaitable` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Aliases to other ABCs in :mod:`collections.abc`
Alias untuk ABC lainnya di :mod:`collections.abc`
Deprecated alias to :class:`collections.abc.Iterable`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Iterable`.
:class:`collections.abc.Iterable` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Iterable` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Iterator`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Iterator`.
:class:`collections.abc.Iterator` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Iterator` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Callable`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Callable`.
See :ref:`annotating-callables` for details on how to use :class:`collections.abc.Callable` and ``typing.Callable`` in type annotations.
Lihat :ref:`annotating-callables` untuk detail tentang cara menggunakan :class:`collections.abc.Callable` dan ``typing.Callable`` dalam anotasi tipe.
:class:`collections.abc.Callable` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Callable` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Generator`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Generator`.
See :ref:`annotating-generators-and-coroutines` for details on using :class:`collections.abc.Generator` and ``typing.Generator`` in type annotations.
Lihat :ref:`annotating-generators-and-coroutines` untuk detail tentang penggunaan :class:`collections.abc.Generator` dan ``typing.Generator`` dalam anotasi tipe.
:class:`collections.abc.Generator` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Generator` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Default values for the send and return types were added.
Nilai default untuk tipe send dan return ditambahkan.
Deprecated alias to :class:`collections.abc.Hashable`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Hashable`.
Use :class:`collections.abc.Hashable` directly instead.
Gunakan :class:`collections.abc.Hashable` secara langsung sebagai gantinya.
Deprecated alias to :class:`collections.abc.Reversible`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Reversible`.
:class:`collections.abc.Reversible` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`collections.abc.Reversible` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Deprecated alias to :class:`collections.abc.Sized`.
Alias yang sudah tidak disarankan lagi untuk :class:`collections.abc.Sized`.
Use :class:`collections.abc.Sized` directly instead.
Gunakan :class:`collections.abc.Sized` secara langsung sebagai gantinya.
Aliases to :mod:`contextlib` ABCs
Alias untuk ABC :mod:`contextlib`
Deprecated alias to :class:`contextlib.AbstractContextManager`.
Alias yang sudah tidak disarankan lagi untuk :class:`contextlib.AbstractContextManager`.
The first type parameter, ``T_co``, represents the type returned by the :meth:`~object.__enter__` method. The optional second type parameter, ``ExitT_co``, which defaults to ``bool | None``, represents the type returned by the :meth:`~object.__exit__` method.
Parameter tipe pertama, ``T_co``, mewakili tipe yang dikembalikan oleh metode :meth:`~object.__enter__`. Parameter tipe kedua yang opsional, ``ExitT_co``, yang nilai default-nya adalah ``bool | None``, mewakili tipe yang dikembalikan oleh metode :meth:`~object.__exit__`.
:class:`contextlib.AbstractContextManager` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`contextlib.AbstractContextManager` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Added the optional second type parameter, ``ExitT_co``.
Parameter tipe kedua yang opsional, ``ExitT_co``, ditambahkan.
Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`.
Alias yang sudah tidak disarankan lagi untuk :class:`contextlib.AbstractAsyncContextManager`.
The first type parameter, ``T_co``, represents the type returned by the :meth:`~object.__aenter__` method. The optional second type parameter, ``AExitT_co``, which defaults to ``bool | None``, represents the type returned by the :meth:`~object.__aexit__` method.
Parameter tipe pertama, ``T_co``, mewakili tipe yang dikembalikan oleh metode :meth:`~object.__aenter__`. Parameter tipe kedua yang opsional, ``AExitT_co``, yang nilai default-nya adalah ``bool | None``, mewakili tipe yang dikembalikan oleh metode :meth:`~object.__aexit__`.
:class:`contextlib.AbstractAsyncContextManager` now supports subscripting (``[]``). See :pep:`585` and :ref:`types-genericalias`.
:class:`contextlib.AbstractAsyncContextManager` kini mendukung operasi subskrip (``[]``). Lihat :pep:`585` dan :ref:`types-genericalias`.
Added the optional second type parameter, ``AExitT_co``.
Parameter tipe kedua yang opsional, ``AExitT_co``, ditambahkan.
Deprecation Timeline of Major Features
Linimasa Penghentian Fitur-Fitur Utama
Certain features in ``typing`` are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.
Fitur-fitur tertentu dalam ``typing`` sudah tidak disarankan lagi dan mungkin dihapus dalam versi Python di masa mendatang. Tabel berikut merangkum penghentian-penghentian utama untuk kemudahan Anda. Hal ini dapat berubah, dan tidak semua penghentian dicantumkan.
Feature
Fitur
Deprecated in
Tidak disarankan lagi sejak
Projected removal
Perkiraan penghapusan
PEP/issue
PEP/issue
``typing`` versions of standard collections
Versi ``typing`` dari koleksi-koleksi standar
3.9
3.9
Undecided (see :ref:`deprecated-aliases` for more information)
Belum diputuskan (lihat :ref:`deprecated-aliases` untuk informasi lebih lanjut)
:pep:`585`
:pep:`585`
:class:`typing.ByteString`
:class:`typing.ByteString`
3.17
3.17
:gh:`91896`
:gh:`91896`
:data:`typing.Text`
:data:`typing.Text`
3.11
3.11
Undecided
Belum diputuskan
:gh:`92332`
:gh:`92332`
:class:`typing.Hashable` and :class:`typing.Sized`
:class:`typing.Hashable` dan :class:`typing.Sized`
3.12
3.12
:gh:`94309`
:gh:`94309`
:data:`typing.TypeAlias`
:data:`typing.TypeAlias`
:pep:`695`
:pep:`695`
:data:`typing.AnyStr`
:data:`typing.AnyStr`
3.13
3.13
3.18
3.18
:gh:`105578`
:gh:`105578`
...
...
ellipsis literal
literal elipsis