Skip to content

Commit 0695faf

Browse files
pzhan9meta-codesync[bot]
authored andcommitted
Add doc string to Future.get (#4115)
Summary: Pull Request resolved: #4115 Using `Future.get` in an async event loop can cause issues, and we are recommending users to avoid using it. But it is still confusing to the user on when is a good time to use `Future.get()`. For example I got [this question](pytorch/torchtitan#3449 (comment)). This diff adds a doc string to this method with a verbose instruction. Reviewed By: mariusae Differential Revision: D106826000 fbshipit-source-id: b677d66e1ab0b229123897df2f058daf6f186217
1 parent 1e9f722 commit 0695faf

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

python/monarch/_src/actor/future.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,38 @@ def __init__(self, *, coro: "Coroutine[Any, Any, R] | PythonTask[R]") -> None:
107107
)
108108

109109
def get(self, timeout: Optional[float] = None) -> R:
110+
"""Get the result of the Future.
111+
112+
Caveats:
113+
114+
This method is designed to be used in places where event loops are not available. Besides that, you should
115+
avoid using this method if possible. Instead, use `await`. This is because when Future.get() is called from
116+
within an active event loop, it blocks synchronously and does not yield control. That may degrade performance
117+
by preventing other tasks from running, and can potentially cause deadlocks if this future depends on them.
118+
119+
examples:
120+
121+
This is not recommended because `fut.get()` blocks the event loop and might lead to issues explained above.
122+
```
123+
def inner_func(fut):
124+
result = fut.get()
125+
# ...
126+
127+
async def out_func(fut):
128+
inner_func(fut)
129+
```
130+
131+
This is okay because everything is running synchronously.
132+
```
133+
def inner_func(fut):
134+
result = fut.get()
135+
# ...
136+
137+
def main():
138+
# ...
139+
inner_func(fut)
140+
```
141+
"""
110142
in_asyncio = asyncio._get_running_loop() is not None
111143
in_tokio = is_tokio_thread()
112144
if in_asyncio or in_tokio:

0 commit comments

Comments
 (0)