Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 599708a

Browse files
martinRenoutacaswell
authored andcommitted
Webagg backend: get rid of tornado
This allows using the webagg backend in JupyterLite, by replacing tornado with asyncio
1 parent a1eef38 commit 599708a

File tree

1 file changed

+24
-25
lines changed

1 file changed

+24
-25
lines changed

lib/matplotlib/backends/backend_webagg_core.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@
88
# way over a web socket.
99
#
1010
# - `backend_webagg.py` contains a concrete implementation of a basic
11-
# application, implemented with tornado.
11+
# application, implemented with asyncio.
1212

13-
import datetime
1413
from io import BytesIO, StringIO
1514
import json
1615
import logging
@@ -19,7 +18,7 @@
1918

2019
import numpy as np
2120
from PIL import Image
22-
import tornado
21+
import asyncio
2322

2423
from matplotlib import _api, backend_bases, backend_tools
2524
from matplotlib.backends import backend_agg
@@ -79,43 +78,43 @@ def _handle_key(key):
7978
return key
8079

8180

82-
class TimerTornado(backend_bases.TimerBase):
81+
class TimerAsyncio(backend_bases.TimerBase):
8382
def __init__(self, *args, **kwargs):
84-
self._timer = None
83+
self._task = None
8584
super().__init__(*args, **kwargs)
8685

86+
async def _timer_task(self, interval):
87+
while True:
88+
try:
89+
await asyncio.sleep(interval)
90+
self._on_timer()
91+
92+
if self._single:
93+
break
94+
except asyncio.CancelledError:
95+
break
96+
8797
def _timer_start(self):
8898
self._timer_stop()
89-
if self._single:
90-
ioloop = tornado.ioloop.IOLoop.instance()
91-
self._timer = ioloop.add_timeout(
92-
datetime.timedelta(milliseconds=self.interval),
93-
self._on_timer)
94-
else:
95-
self._timer = tornado.ioloop.PeriodicCallback(
96-
self._on_timer,
97-
max(self.interval, 1e-6))
98-
self._timer.start()
99+
100+
self._task = asyncio.ensure_future(
101+
self._timer_task(max(self.interval / 1_000., 1e-6))
102+
)
99103

100104
def _timer_stop(self):
101-
if self._timer is None:
102-
return
103-
elif self._single:
104-
ioloop = tornado.ioloop.IOLoop.instance()
105-
ioloop.remove_timeout(self._timer)
106-
else:
107-
self._timer.stop()
108-
self._timer = None
105+
if self._task is not None:
106+
self._task.cancel()
107+
self._task = None
109108

110109
def _timer_set_interval(self):
111110
# Only stop and restart it if the timer has already been started
112-
if self._timer is not None:
111+
if self._task is not None:
113112
self._timer_stop()
114113
self._timer_start()
115114

116115

117116
class FigureCanvasWebAggCore(backend_agg.FigureCanvasAgg):
118-
_timer_cls = TimerTornado
117+
_timer_cls = TimerAsyncio
119118
# Webagg and friends having the right methods, but still
120119
# having bugs in practice. Do not advertise that it works until
121120
# we can debug this.

0 commit comments

Comments
 (0)