Source text — English
Translation — Bahasa Indonesia
Futures
Future
**Source code:** :source:`Lib/asyncio/futures.py`, :source:`Lib/asyncio/base_futures.py`
**Kode sumber:** :source:`Lib/asyncio/futures.py`, :source:`Lib/asyncio/base_futures.py`
*Future* objects are used to bridge **low-level callback-based code** with high-level async/await code.
Objek *Future* digunakan untuk menjembatani **kode berbasis callback tingkat rendah** dengan kode async/await tingkat tinggi.
Future Functions
Fungsi Future
Return ``True`` if *obj* is either of:
Mengembalikan ``True`` jika *obj* adalah salah satu dari:
an instance of :class:`asyncio.Future`,
sebuah instance dari :class:`asyncio.Future`,
an instance of :class:`asyncio.Task`,
sebuah instance dari :class:`asyncio.Task`,
a Future-like object with a ``_asyncio_future_blocking`` attribute.
objek mirip-Future dengan atribut ``_asyncio_future_blocking``.
Return:
Mengembalikan:
*obj* argument as is, if *obj* is a :class:`Future`, a :class:`Task`, or a Future-like object (:func:`isfuture` is used for the test.)
argumen *obj* apa adanya, jika *obj* adalah :class:`Future`, :class:`Task`, atau objek mirip-Future (:func:`isfuture` digunakan untuk pengujian.)
a :class:`Task` object wrapping *obj*, if *obj* is a coroutine (:func:`iscoroutine` is used for the test); in this case the coroutine will be scheduled by ``ensure_future()``.
objek :class:`Task` yang membungkus *obj*, jika *obj* adalah coroutine (:func:`iscoroutine` digunakan untuk pengujian); dalam hal ini coroutine akan dijadwalkan oleh ``ensure_future()``.
a :class:`Task` object that would await on *obj*, if *obj* is an awaitable (:func:`inspect.isawaitable` is used for the test.)
objek :class:`Task` yang akan menunggu *obj*, jika *obj* adalah awaitable (:func:`inspect.isawaitable` digunakan untuk pengujian.)
If *obj* is neither of the above a :exc:`TypeError` is raised.
Jika *obj* bukan salah satu dari di atas, :exc:`TypeError` akan dimunculkan.
Save a reference to the result of this function, to avoid a task disappearing mid-execution.
Simpan referensi ke hasil fungsi ini, untuk menghindari task yang hilang di tengah eksekusi.
See also the :func:`create_task` function which is the preferred way for creating new tasks or use :class:`asyncio.TaskGroup` which keeps reference to the task internally.
Lihat juga fungsi :func:`create_task` yang merupakan cara yang lebih disarankan untuk membuat task baru, atau gunakan :class:`asyncio.TaskGroup` yang menyimpan referensi ke task secara internal.
The function accepts any :term:`awaitable` object.
Fungsi ini menerima objek :term:`awaitable` apa pun.
Deprecation warning is emitted if *obj* is not a Future-like object and *loop* is not specified and there is no running event loop.
Peringatan pengusangan dimunculkan jika *obj* bukan objek mirip-Future dan *loop* tidak ditentukan dan tidak ada event loop yang sedang berjalan.
Wrap a :class:`concurrent.futures.Future` object in a :class:`asyncio.Future` object.
Membungkus objek :class:`concurrent.futures.Future` dalam objek :class:`asyncio.Future`.
Deprecation warning is emitted if *future* is not a Future-like object and *loop* is not specified and there is no running event loop.
Peringatan pengusangan dimunculkan jika *future* bukan objek mirip-Future dan *loop* tidak ditentukan dan tidak ada event loop yang sedang berjalan.
Future Object
Objek Future
A Future represents an eventual result of an asynchronous operation. Not thread-safe.
Future merepresentasikan hasil akhir dari sebuah operasi asinkron. Tidak aman terhadap thread.
Future is an :term:`awaitable` object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled. A Future can be awaited multiple times and the result is same.
Future adalah objek :term:`awaitable`. Coroutine dapat menunggu objek Future sampai objek tersebut memiliki hasil atau exception yang ditetapkan, atau sampai dibatalkan. Sebuah Future dapat ditunggu beberapa kali dan hasilnya sama.
Typically Futures are used to enable low-level callback-based code (e.g. in protocols implemented using asyncio :ref:`transports <asyncio-transports-protocols>`) to interoperate with high-level async/await code.
Biasanya Future digunakan untuk memungkinkan kode berbasis callback tingkat rendah (misalnya dalam protokol yang diimplementasikan menggunakan asyncio :ref:`transports <asyncio-transports-protocols>`) berinteroperasi dengan kode async/await tingkat tinggi.
The rule of thumb is to never expose Future objects in user-facing APIs, and the recommended way to create a Future object is to call :meth:`loop.create_future`. This way alternative event loop implementations can inject their own optimized implementations of a Future object.
Aturan umumnya adalah jangan pernah mengekspos objek Future dalam API yang digunakan pengguna, dan cara yang disarankan untuk membuat objek Future adalah dengan memanggil :meth:`loop.create_future`. Dengan cara ini implementasi event loop alternatif dapat menyuntikkan implementasi Future-nya sendiri yang sudah dioptimalkan.
Futures are :ref:`generic <generics>` over the type of their results.
Future bersifat :ref:`generic <generics>` terhadap tipe hasilnya.
Added support for the :mod:`contextvars` module.
Menambahkan dukungan untuk modul :mod:`contextvars`.
Deprecation warning is emitted if *loop* is not specified and there is no running event loop.
Peringatan pengusangan dimunculkan jika *loop* tidak ditentukan dan tidak ada event loop yang sedang berjalan.
Return the result of the Future.
Mengembalikan hasil dari Future.
If the Future is *done* and has a result set by the :meth:`set_result` method, the result value is returned.
Jika Future *selesai* (*done*) dan memiliki hasil yang ditetapkan oleh metode :meth:`set_result`, nilai hasilnya dikembalikan.
If the Future is *done* and has an exception set by the :meth:`set_exception` method, this method raises the exception.
Jika Future *selesai* dan memiliki exception yang ditetapkan oleh metode :meth:`set_exception`, metode ini memunculkan exception tersebut.
If the Future has been *cancelled*, this method raises a :exc:`CancelledError` exception.
Jika Future telah *dibatalkan* (*cancelled*), metode ini memunculkan exception :exc:`CancelledError`.
If the Future's result isn't yet available, this method raises an :exc:`InvalidStateError` exception.
Jika hasil Future belum tersedia, metode ini memunculkan exception :exc:`InvalidStateError`.
Mark the Future as *done* and set its result.
Menandai Future sebagai *selesai* dan menetapkan hasilnya.
Raises an :exc:`InvalidStateError` error if the Future is already *done*.
Memunculkan galat :exc:`InvalidStateError` jika Future sudah *selesai*.
Mark the Future as *done* and set an exception.
Menandai Future sebagai *selesai* dan menetapkan sebuah exception.
Return ``True`` if the Future is *done*.
Mengembalikan ``True`` jika Future *selesai*.
A Future is *done* if it was *cancelled* or if it has a result or an exception set with :meth:`set_result` or :meth:`set_exception` calls.
Sebuah Future *selesai* jika Future tersebut *dibatalkan* atau jika memiliki hasil atau exception yang ditetapkan melalui panggilan :meth:`set_result` atau :meth:`set_exception`.
Return ``True`` if the Future was *cancelled*.
Mengembalikan ``True`` jika Future *dibatalkan*.
The method is usually used to check if a Future is not *cancelled* before setting a result or an exception for it::
Metode ini biasanya digunakan untuk memeriksa apakah sebuah Future belum *dibatalkan* sebelum menetapkan hasil atau exception untuknya::
if not fut.cancelled():
fut.set_result(42)
if not fut.cancelled():
fut.set_result(42)
Add a callback to be run when the Future is *done*.
Menambahkan callback yang akan dijalankan saat Future *selesai*.
The *callback* is called with the Future object as its only argument.
*callback* dipanggil dengan objek Future sebagai satu-satunya argumen.
If the Future is already *done* when this method is called, the callback is scheduled with :meth:`loop.call_soon`.
Jika Future sudah *selesai* saat metode ini dipanggil, callback dijadwalkan dengan :meth:`loop.call_soon`.
An optional keyword-only *context* argument allows specifying a custom :class:`contextvars.Context` for the *callback* to run in. The current context is used when no *context* is provided.
Argumen *context* opsional khusus keyword memungkinkan penentuan :class:`contextvars.Context` kustom bagi *callback* untuk berjalan. Konteks saat ini digunakan ketika tidak ada *context* yang diberikan.
:func:`functools.partial` can be used to pass parameters to the callback, e.g.::
:func:`functools.partial` dapat digunakan untuk meneruskan parameter ke callback, misalnya::
# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
functools.partial(print, "Future:"))
# Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
functools.partial(print, "Future:"))
The *context* keyword-only parameter was added. See :pep:`567` for more details.
Parameter *context* khusus keyword telah ditambahkan. Lihat :pep:`567` untuk detail selengkapnya.
Remove *callback* from the callbacks list.
Menghapus *callback* dari daftar callback.
Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.
Mengembalikan jumlah callback yang dihapus, yang biasanya 1, kecuali sebuah callback ditambahkan lebih dari satu kali.
Cancel the Future and schedule callbacks.
Membatalkan Future dan menjadwalkan callback.
If the Future is already *done* or *cancelled*, return ``False``. Otherwise, change the Future's state to *cancelled*, schedule the callbacks, and return ``True``.
Jika Future sudah *selesai* atau *dibatalkan*, mengembalikan ``False``. Jika tidak, mengubah status Future menjadi *dibatalkan*, menjadwalkan callback, dan mengembalikan ``True``.
The optional string argument *msg* is passed as the argument to the :exc:`CancelledError` exception raised when a cancelled Future is awaited.
Argumen string opsional *msg* diteruskan sebagai argumen ke exception :exc:`CancelledError` yang dimunculkan saat Future yang dibatalkan ditunggu.
Added the *msg* parameter.
Menambahkan parameter *msg*.
Return the exception that was set on this Future.
Mengembalikan exception yang ditetapkan pada Future ini.
The exception (or ``None`` if no exception was set) is returned only if the Future is *done*.
Exception (atau ``None`` jika tidak ada exception yang ditetapkan) dikembalikan hanya jika Future *selesai*.
If the Future isn't *done* yet, this method raises an :exc:`InvalidStateError` exception.
Jika Future belum *selesai*, metode ini memunculkan exception :exc:`InvalidStateError`.
Return the event loop the Future object is bound to.
Mengembalikan event loop yang terikat pada objek Future.
This example creates a Future object, creates and schedules an asynchronous Task to set result for the Future, and waits until the Future has a result::
Contoh ini membuat objek Future, membuat dan menjadwalkan Task asinkron untuk menetapkan hasil bagi Future, dan menunggu sampai Future memiliki hasil::
async def set_after(fut, delay, value):
# Sleep for *delay* seconds.
await asyncio.sleep(delay)
# Set *value* as a result of *fut* Future.
fut.set_result(value)
async def main():
# Get the current event loop.
loop = asyncio.get_running_loop()
# Create a new Future object.
fut = loop.create_future()
# Run "set_after()" coroutine in a parallel Task.
# We are using the low-level "loop.create_task()" API here because
# we already have a reference to the event loop at hand.
# Otherwise we could have just used "asyncio.create_task()".
loop.create_task(
set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it.
print(await fut)
asyncio.run(main())
async def set_after(fut, delay, value):
# Sleep for *delay* seconds.
await asyncio.sleep(delay)
# Set *value* as a result of *fut* Future.
fut.set_result(value)
async def main():
# Get the current event loop.
loop = asyncio.get_running_loop()
# Create a new Future object.
fut = loop.create_future()
# Run "set_after()" coroutine in a parallel Task.
# We are using the low-level "loop.create_task()" API here because
# we already have a reference to the event loop at hand.
# Otherwise we could have just used "asyncio.create_task()".
loop.create_task(
set_after(fut, 1, '... world'))
print('hello ...')
# Wait until *fut* has a result (1 second) and print it.
print(await fut)
asyncio.run(main())
The Future object was designed to mimic :class:`concurrent.futures.Future`. Key differences include:
Objek Future dirancang untuk meniru :class:`concurrent.futures.Future`. Perbedaan utamanya meliputi:
unlike asyncio Futures, :class:`concurrent.futures.Future` instances cannot be awaited.
tidak seperti Future asyncio, instance :class:`concurrent.futures.Future` tidak dapat ditunggu.
:meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` do not accept the *timeout* argument.
:meth:`asyncio.Future.result` dan :meth:`asyncio.Future.exception` tidak menerima argumen *timeout*.
:meth:`asyncio.Future.result` and :meth:`asyncio.Future.exception` raise an :exc:`InvalidStateError` exception when the Future is not *done*.
:meth:`asyncio.Future.result` dan :meth:`asyncio.Future.exception` memunculkan exception :exc:`InvalidStateError` saat Future tidak *selesai*.
Callbacks registered with :meth:`asyncio.Future.add_done_callback` are not called immediately. They are scheduled with :meth:`loop.call_soon` instead.
Callback yang didaftarkan dengan :meth:`asyncio.Future.add_done_callback` tidak langsung dipanggil. Callback tersebut dijadwalkan dengan :meth:`loop.call_soon`.
asyncio Future is not compatible with the :func:`concurrent.futures.wait` and :func:`concurrent.futures.as_completed` functions.
Future asyncio tidak kompatibel dengan fungsi :func:`concurrent.futures.wait` dan :func:`concurrent.futures.as_completed`.
:meth:`asyncio.Future.cancel` accepts an optional ``msg`` argument, but :meth:`concurrent.futures.Future.cancel` does not.
:meth:`asyncio.Future.cancel` menerima argumen ``msg`` opsional, tetapi :meth:`concurrent.futures.Future.cancel` tidak.