Skip to content

Commit 581680e

Browse files
committed
Inject class instance into routines used in classes.
1 parent f0db54d commit 581680e

File tree

1 file changed

+35
-3
lines changed

1 file changed

+35
-3
lines changed

twitchio/ext/routines/__init__.py

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,29 @@ def __init__(
9595

9696
self._stop_on_error = True
9797

98+
self._instance = None
99+
100+
def __get__(self, instance, owner):
101+
if instance is None:
102+
return self
103+
104+
copy = Routine(
105+
coro=self._coro,
106+
loop=self._loop,
107+
iterations=self._iterations,
108+
time=self._time,
109+
delta=self._delta,
110+
wait_first=self._wait_first,
111+
)
112+
113+
copy._instance = instance
114+
copy._before = self._before
115+
copy._after = self._after
116+
copy._error = self._error
117+
setattr(instance, self._coro.__name__, copy)
118+
119+
return copy
120+
98121
def start(self, *args, **kwargs) -> asyncio.Task:
99122
"""Start the routine and return the created task.
100123
@@ -248,7 +271,10 @@ async def _routine(self, *args, **kwargs) -> None:
248271

249272
try:
250273
if self._before:
251-
await self._before()
274+
if self._instance:
275+
await self._before(self._instance)
276+
else:
277+
await self._before()
252278
except Exception as e:
253279
await self._error(e)
254280

@@ -266,7 +292,10 @@ async def _routine(self, *args, **kwargs) -> None:
266292
start = datetime.datetime.now(datetime.timezone.utc)
267293

268294
try:
269-
await self._coro(*args, **kwargs)
295+
if self._instance:
296+
await self._coro(self._instance, *args, **kwargs)
297+
else:
298+
await self._coro(*args, **kwargs)
270299
except Exception as e:
271300
await self._error(e)
272301

@@ -295,7 +324,10 @@ async def _routine(self, *args, **kwargs) -> None:
295324

296325
try:
297326
if self._after:
298-
await self._after()
327+
if self._instance:
328+
await self._after(self._instance)
329+
else:
330+
await self._after()
299331
except Exception as e:
300332
await self._error(e)
301333
finally:

0 commit comments

Comments
 (0)