Skip to content

Commit 080deae

Browse files
jbmscopybara-github
authored andcommitted
Allow Python Future and Promise classes to behave like generic classes
PiperOrigin-RevId: 823076226 Change-Id: I9edd345d77f2cb9860f0da22168e8e0a21bf44e7
1 parent 1afa3bf commit 080deae

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

python/tensorstore/future.cc

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,13 +703,20 @@ See also:
703703
Group:
704704
Asynchronous support
705705
)";
706+
707+
static const PyMethodDef future_methods[] = {
708+
{"__class_getitem__", Py_GenericAlias, METH_O | METH_CLASS, ""},
709+
{nullptr},
710+
};
706711
PyType_Slot slots[] = {
707712
{Py_tp_doc, const_cast<char*>(doc)},
708713
{Py_tp_alloc, reinterpret_cast<void*>(&FutureAlloc)},
709714
{Py_tp_dealloc, reinterpret_cast<void*>(&FutureDealloc)},
710715
{Py_tp_traverse, reinterpret_cast<void*>(&FutureTraverse)},
711716
{Py_tp_clear, reinterpret_cast<void*>(&FutureClear)},
712717
{Py_tp_finalize, reinterpret_cast<void*>(&FutureFinalize)},
718+
{Py_tp_methods,
719+
const_cast<void*>(reinterpret_cast<const void*>(future_methods))},
713720
{0, nullptr},
714721
};
715722
PyType_Spec spec = {};
@@ -1025,12 +1032,18 @@ See also:
10251032
Group:
10261033
Asynchronous support
10271034
)";
1035+
static const PyMethodDef promise_methods[] = {
1036+
{"__class_getitem__", Py_GenericAlias, METH_O | METH_CLASS, ""},
1037+
{nullptr},
1038+
};
10281039
PyType_Slot slots[] = {
10291040
{Py_tp_doc, const_cast<char*>(doc)},
10301041
{Py_tp_alloc, reinterpret_cast<void*>(&PromiseAlloc)},
10311042
{Py_tp_dealloc, reinterpret_cast<void*>(&PromiseDealloc)},
10321043
{Py_tp_traverse, reinterpret_cast<void*>(&PromiseTraverse)},
10331044
{Py_tp_clear, reinterpret_cast<void*>(&PromiseClear)},
1045+
{Py_tp_methods,
1046+
const_cast<void*>(reinterpret_cast<const void*>(promise_methods))},
10341047
{0, nullptr},
10351048
};
10361049
PyType_Spec spec = {};

python/tensorstore/tests/future_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import signal
1919
import threading
2020
import time
21+
import types
2122

2223
import pytest
2324
import tensorstore as ts
@@ -31,6 +32,11 @@ def test_promise_new():
3132
assert future.result() == 5
3233

3334

35+
def test_type_params():
36+
assert ts.Promise[int] == types.GenericAlias(ts.Promise, (int,))
37+
assert ts.Future[int] == types.GenericAlias(ts.Future, (int,))
38+
39+
3440
def test_promise_result_release_gil():
3541
promise, future = ts.Promise.new()
3642
t = threading.Thread(target=future.result)

0 commit comments

Comments
 (0)