Skip to content

Commit dad6be5

Browse files
asvetlovmiss-islington
authored andcommitted
bpo-38785: Prevent asyncio from crashing (GH-17144)
if parent `__init__` is not called from a constructor of object derived from `asyncio.Future` https://bugs.python.org/issue38785
1 parent 61289d4 commit dad6be5

File tree

4 files changed

+46
-1
lines changed

4 files changed

+46
-1
lines changed

Lib/asyncio/futures.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,10 @@ def _log_traceback(self, val):
115115

116116
def get_loop(self):
117117
"""Return the event loop the Future is bound to."""
118-
return self._loop
118+
loop = self._loop
119+
if loop is None:
120+
raise RuntimeError("Future object is not initialized.")
121+
return loop
119122

120123
def cancel(self):
121124
"""Cancel the future and schedule callbacks.

Lib/test/test_asyncio/test_futures.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -822,5 +822,44 @@ def _new_future(self):
822822
return futures._PyFuture(loop=self.loop)
823823

824824

825+
class BaseFutureInheritanceTests:
826+
827+
def _get_future_cls(self):
828+
raise NotImplementedError
829+
830+
def setUp(self):
831+
super().setUp()
832+
self.loop = self.new_test_loop()
833+
self.addCleanup(self.loop.close)
834+
835+
def test_inherit_without_calling_super_init(self):
836+
# See https://bugs.python.org/issue38785 for the context
837+
cls = self._get_future_cls()
838+
839+
class MyFut(cls):
840+
def __init__(self, *args, **kwargs):
841+
# don't call super().__init__()
842+
pass
843+
844+
fut = MyFut(loop=self.loop)
845+
with self.assertRaisesRegex(
846+
RuntimeError,
847+
"Future object is not initialized."
848+
):
849+
fut.get_loop()
850+
851+
852+
class PyFutureInheritanceTests(BaseFutureInheritanceTests,
853+
test_utils.TestCase):
854+
def _get_future_cls(self):
855+
return futures._PyFuture
856+
857+
858+
class CFutureInheritanceTests(BaseFutureInheritanceTests,
859+
test_utils.TestCase):
860+
def _get_future_cls(self):
861+
return futures._CFuture
862+
863+
825864
if __name__ == '__main__':
826865
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Prevent asyncio from crashing if parent ``__init__`` is not called from a
2+
constructor of object derived from ``asyncio.Future``.

Modules/_asynciomodule.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,6 +1091,7 @@ static PyObject *
10911091
_asyncio_Future_get_loop_impl(FutureObj *self)
10921092
/*[clinic end generated code: output=119b6ea0c9816c3f input=cba48c2136c79d1f]*/
10931093
{
1094+
ENSURE_FUTURE_ALIVE(self)
10941095
Py_INCREF(self->fut_loop);
10951096
return self->fut_loop;
10961097
}

0 commit comments

Comments
 (0)