Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Add type hints for ObservableDeferred attributes #12159

Merged
merged 1 commit into from
Mar 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/12159.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add type hints for `ObservableDeferred` attributes.
14 changes: 11 additions & 3 deletions synapse/util/async_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
)

import attr
from typing_extensions import ContextManager
from typing_extensions import ContextManager, Literal

from twisted.internet import defer
from twisted.internet.defer import CancelledError
Expand Down Expand Up @@ -96,6 +96,10 @@ class ObservableDeferred(Generic[_T], AbstractObservableDeferred[_T]):

__slots__ = ["_deferred", "_observers", "_result"]

_deferred: "defer.Deferred[_T]"
_observers: Union[List["defer.Deferred[_T]"], Tuple[()]]
_result: Union[None, Tuple[Literal[True], _T], Tuple[Literal[False], Failure]]
Comment on lines +100 to +101
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aside: I really wish Python type hints weren't so verbose.


def __init__(self, deferred: "defer.Deferred[_T]", consumeErrors: bool = False):
object.__setattr__(self, "_deferred", deferred)
object.__setattr__(self, "_result", None)
Expand Down Expand Up @@ -158,12 +162,14 @@ def observe(self) -> "defer.Deferred[_T]":
effect the underlying deferred.
"""
if not self._result:
assert isinstance(self._observers, list)
d: "defer.Deferred[_T]" = defer.Deferred()
self._observers.append(d)
return d
elif self._result[0]:
return defer.succeed(self._result[1])
else:
success, res = self._result
return defer.succeed(res) if success else defer.fail(res)
return defer.fail(self._result[1])

def observers(self) -> "Collection[defer.Deferred[_T]]":
return self._observers
Expand All @@ -175,6 +181,8 @@ def has_succeeded(self) -> bool:
return self._result is not None and self._result[0] is True

def get_result(self) -> Union[_T, Failure]:
if self._result is None:
raise ValueError(f"{self!r} has no result yet")
return self._result[1]

def __getattr__(self, name: str) -> Any:
Expand Down