Skip to content
Open
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
6 changes: 3 additions & 3 deletions a_sync/a_sync/_helpers.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ and converting synchronous functions to asynchronous ones.
from asyncio import iscoroutinefunction, new_event_loop, set_event_loop
from asyncio import get_event_loop as _get_event_loop
from asyncio.futures import _chain_future
from cpython.object cimport PyObject, PyObject_CallMethodObjArgs

from a_sync import exceptions
from a_sync._typing import *
Expand Down Expand Up @@ -46,7 +47,7 @@ cdef object _await(object awaitable):
- :func:`asyncio.run`: For running the main entry point of an asyncio program.
"""
try:
return get_event_loop().run_until_complete(awaitable)
return PyObject_CallMethodObjArgs(get_event_loop(), "run_until_complete", <PyObject*>awaitable, NULL)
except RuntimeError as e:
if str(e) == "This event loop is already running":
raise exceptions.SyncModeInAsyncContextError from None
Expand Down Expand Up @@ -111,8 +112,7 @@ cdef object _asyncify(object func, executor: Executor): # type: ignore [misc]

@wraps(func)
async def _asyncify_wrap(*args: P.args, **kwargs: P.kwargs) -> T:
loop = get_event_loop()
fut = loop.create_future()
fut = PyObject_CallMethodObjArgs(get_event_loop(), "create_future", NULL)
cf_fut = submit(func, *args, **kwargs)
_chain_future(cf_fut, fut)
return await fut
Expand Down
2 changes: 1 addition & 1 deletion a_sync/a_sync/modifiers/manager.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ cdef class ModifierManager:
>>> list(iter(manager))
['cache_type']
"""
return self._modifiers.__iter__()
return iter(self._modifiers)

def __len__(self) -> uint8_t:
"""Returns the number of modifiers.
Expand Down
25 changes: 18 additions & 7 deletions a_sync/async_property/proxy.pyx
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
from cpython.object cimport PyObject, PyObject_CallFunctionObjArgs, PyObject_CallMethodObjArgs


cdef class AwaitableOnly:
"""This wraps a coroutine will call it on await."""

def __init__(self, coro):
def __cinit__(self, object coro):
self._coro = coro

def __repr__(self):
return f'<AwaitableOnly "{self._coro.__qualname__}">'

def __await__(self):
return self._coro().__await__()
return PyObject_CallMethodObjArgs(
PyObject_CallFunctionObjArgs(self._coro, NULL),
"__await__",
NULL,
)


# PURE PYTHON
Expand Down Expand Up @@ -422,7 +429,7 @@ class ObjectProxy(metaclass=_ObjectProxyMetaType):
del self.__wrapped__[i:j]

def __enter__(self):
return self.__wrapped__.__enter__()
return PyObject_CallMethodObjArgs(self.__wrapped__, "__enter__", NULL)

def __exit__(self, *args, **kwargs):
return self.__wrapped__.__exit__(*args, **kwargs)
Expand Down Expand Up @@ -450,19 +457,23 @@ class ObjectProxy(metaclass=_ObjectProxyMetaType):

class AwaitableProxy(ObjectProxy):
def __await__(self):
return self.__get_wrapped().__await__()
return PyObject_CallMethodObjArgs(
PyObject_CallMethodObjArgs(self, "_AwaitableProxy__get_wrapped", NULL),
"__await__",
NULL,
)

async def __aenter__(self):
return await self.__wrapped__.__aenter__()
return await PyObject_CallMethodObjArgs(self.__wrapped__, "__aenter__", NULL)

async def __aexit__(self, *args, **kwargs):
return await self.__wrapped__.__aexit__(*args, **kwargs)

async def __aiter__(self):
return await self.__wrapped__.__aiter__()
return await PyObject_CallMethodObjArgs(self.__wrapped__, "__aiter__", NULL)

async def __anext__(self):
return await self.__wrapped__.__anext__()
return await PyObject_CallMethodObjArgs(self.__wrapped__, "__anext__", NULL)

async def __get_wrapped(self):
return self.__wrapped__
10 changes: 8 additions & 2 deletions a_sync/asyncio/create_task.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ manage task lifecycle, and enhance error handling.

import asyncio.tasks as aiotasks
from asyncio import Future, InvalidStateError, Task, get_running_loop, iscoroutine
from cpython.object cimport PyObject, PyObject_CallMethodObjArgs
from logging import getLogger

from a_sync._smart import SmartTask, smart_task_factory
Expand Down Expand Up @@ -180,7 +181,12 @@ cdef void __prune_persisted_tasks():
}
if task._source_traceback:
context["source_traceback"] = task._source_traceback
task._loop.call_exception_handler(context)
PyObject_CallMethodObjArgs(
task._loop,
"call_exception_handler",
<PyObject*>context,
NULL,
)


cdef inline bint _is_done(fut: Future):
Expand All @@ -200,7 +206,7 @@ cdef object _get_exception(fut: Future):
fut._Future__log_traceback = False
return fut._exception
if state == "CANCELLED":
raise fut._make_cancelled_error()
raise PyObject_CallMethodObjArgs(fut, "_make_cancelled_error", NULL)
raise InvalidStateError('Exception is not set.')


Expand Down
9 changes: 5 additions & 4 deletions a_sync/primitives/_debug.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ The mixin provides a framework for managing a debug daemon task, which can be us
import os
from asyncio import AbstractEventLoop, Future, Task
from asyncio.events import _running_loop
from cpython.object cimport PyObject_CallMethodObjArgs
from threading import Lock
from typing import Optional

Expand Down Expand Up @@ -134,9 +135,9 @@ cdef class _DebugDaemonMixin(_LoopBoundMixin):

cdef object _c_start_debug_daemon(self, tuple[object] args, dict[str, object] kwargs):
cdef object loop = self._c_get_loop()
if self.check_debug_logs_enabled() and loop.is_running():
if self.check_debug_logs_enabled() and PyObject_CallMethodObjArgs(loop, "is_running", NULL) is True:
return ccreate_task_simple(self._debug_daemon(*args, **kwargs))
return loop.create_future()
return PyObject_CallMethodObjArgs(loop, "create_future", NULL)

def _ensure_debug_daemon(self, *args, **kwargs) -> None:
"""
Expand Down Expand Up @@ -173,7 +174,7 @@ cdef class _DebugDaemonMixin(_LoopBoundMixin):
daemon.add_done_callback(self._stop_debug_daemon)
self._daemon = daemon
else:
self._daemon = self._c_get_loop().create_future()
self._daemon = PyObject_CallMethodObjArgs(self._c_get_loop(), "create_future", NULL)

self._has_daemon = True

Expand Down Expand Up @@ -202,6 +203,6 @@ cdef class _DebugDaemonMixin(_LoopBoundMixin):
"""
if t and t != self._daemon:
raise ValueError(f"{t} is not {self._daemon}")
t.cancel()
PyObject_CallMethodObjArgs(t, "cancel", NULL)
self._daemon = None
self._has_daemon = False
7 changes: 5 additions & 2 deletions a_sync/primitives/_loggable.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
This module provides a mixin class to add debug logging capabilities to other classes.
"""

from cpython.object cimport PyObject, PyObject_CallMethodObjArgs
from logging import Logger, getLogger, DEBUG


cdef PyObject* _DEBUG = <PyObject*>DEBUG

cdef class _LoggerMixin:
"""
A mixin class that adds logging capabilities to other classes.
Expand Down Expand Up @@ -80,10 +83,10 @@ cdef class _LoggerMixin:
See Also:
- :attr:`logging.Logger.isEnabledFor`
"""
return self.get_logger().isEnabledFor(DEBUG)
return PyObject_CallMethodObjArgs(self.get_logger(), "isEnabledFor", _DEBUG, NULL)

cdef inline bint check_debug_logs_enabled(self):
return self.get_logger().isEnabledFor(DEBUG)
return PyObject_CallMethodObjArgs(self.get_logger(), "isEnabledFor", _DEBUG, NULL)


cdef dict[str, object] _class_loggers = {}
Expand Down
Loading
Loading