@@ -141,10 +141,28 @@ def __init__(
141141 )
142142 if not isinstance (overlap , (bool , int )):
143143 raise TypeError ("overlap must be a bool or a positive integer." )
144- elif not isinstance (overlap , bool ) and isinstance (overlap , int ):
144+
145+ if isinstance (overlap , bool ):
146+ if overlap is True :
147+ self ._run_with_semaphore = self ._run_direct
148+ else :
145149 if overlap <= 1 :
146150 raise ValueError ("overlap as an integer must be greater than 1." )
147151 self ._semaphore = asyncio .Semaphore (overlap )
152+ self ._run_with_semaphore = self ._make_semaphore_runner ()
153+
154+ async def _run_direct (self , * args : Any , ** kwargs : Any ) -> None :
155+ """Run the coroutine directly."""
156+ await self .coro (* args , ** kwargs )
157+
158+ def _make_semaphore_runner (self ) -> Callable [..., Awaitable [None ]]:
159+ """Return a function that runs the coroutine with a semaphore."""
160+
161+ async def runner (* args : Any , ** kwargs : Any ) -> None :
162+ async with self ._semaphore :
163+ await self .coro (* args , ** kwargs )
164+
165+ return runner
148166
149167 async def _call_loop_function (self , name : str , * args : Any , ** kwargs : Any ) -> None :
150168 coro = getattr (self , f"_{ name } " )
@@ -187,17 +205,8 @@ async def _loop(self, *args: Any, **kwargs: Any) -> None:
187205 if not self .overlap :
188206 await self .coro (* args , ** kwargs )
189207 else :
190-
191- async def run_with_semaphore ():
192- async with self ._semaphore :
193- await self .coro (* args , ** kwargs )
194-
195208 task = asyncio .create_task (
196- (
197- self .coro (* args , ** kwargs )
198- if self .overlap is True
199- else run_with_semaphore ()
200- ),
209+ self ._run_with_semaphore (* args , ** kwargs ),
201210 name = f"pycord-loop-{ self .coro .__name__ } -{ self ._current_loop } " ,
202211 )
203212 task .add_done_callback (self ._tasks .remove )
0 commit comments