Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
BobTheBuidler committed Feb 25, 2023
0 parents commit 8826d0d
Show file tree
Hide file tree
Showing 17 changed files with 319 additions and 0 deletions.
24 changes: 24 additions & 0 deletions .github/workflows/mypy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: MyPy

on: pull_request

jobs:
mypy:
runs-on: ubuntu-20.04

steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0

- name: Setup Python (faster than using Python container)
uses: actions/setup-python@v2
with:
python-version: "3.9"

- name: Install MyPy
run: |
python -m pip install --upgrade pip
pip install mypy types-requests
- name: Run MyPy
run: mypy . --pretty --ignore-missing-imports --show-error-codes --show-error-context
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
env/
.mypy_cache/
.pytest_cache/
__pycache__/
17 changes: 17 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
MIT License
Copyright (c) 2023 Posted On The Block LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions a_sync/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@

from a_sync.base import ASyncBase
from a_sync.decorator import a_sync
57 changes: 57 additions & 0 deletions a_sync/_bound.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@

import functools
from inspect import isawaitable
from typing import Any, Callable, TypeVar, Union, overload, Awaitable

from async_property.base import AsyncPropertyDescriptor
from async_property.cached import AsyncCachedPropertyDescriptor
from typing_extensions import ParamSpec # type: ignore

from a_sync import _helpers
from a_sync.decorator import a_sync as unbound_a_sync

P = ParamSpec("P")
T = TypeVar("T")


def a_sync(coro_fn: Callable[P, T]) -> Callable[P, T]: # type: ignore
# First we wrap the coro_fn so overriding kwargs are handled automagically.
wrapped_coro_fn = unbound_a_sync(coro_fn)

@functools.wraps(coro_fn)
def bound_a_sync_wrap(self, *args: P.args, **kwargs: P.kwargs) -> T: # type: ignore
from a_sync.base import ASyncBase
if not isinstance(self, ASyncBase):
raise RuntimeError(f"{self} must be an instance of a class that inherits from ASyncBase")
# This could either be a coroutine or a return value from an awaited coroutine,
# depending on if an overriding kwarg was passed into the function call.
retval_or_coro = wrapped_coro_fn(self, *args, **kwargs)
if not isawaitable(retval_or_coro):
# The coroutine was already awaited due to the use of an overriding kwarg.
# We can return the value.
return retval_or_coro
# The awaitable was not awaited, so now we need to check the flag as defined on 'self' and await if appropriate.
return _helpers._await_if_sync(retval_or_coro, self._should_await(kwargs)) # type: ignore
return bound_a_sync_wrap


@overload
def a_sync_property(async_property: AsyncPropertyDescriptor) -> AsyncPropertyDescriptor:
...
@overload
def a_sync_property(async_property: AsyncCachedPropertyDescriptor) -> AsyncCachedPropertyDescriptor: # type: ignore
...
def a_sync_property(async_property):
if not isinstance(async_property, (AsyncPropertyDescriptor, AsyncCachedPropertyDescriptor)):
raise TypeError(f"{async_property} must be one of: AsyncPropertyDescriptor, AsyncCachedPropertyDescriptor")

from a_sync.base import ASyncBase

@property
@functools.wraps(async_property)
def a_sync_property_wrap(self) -> T:
if not isinstance(self, ASyncBase):
raise RuntimeError(f"{self} must be an instance of a class that inherits from ASyncBase")
awaitable: Awaitable[T] = async_property.__get__(self, async_property)
return _helpers._await_if_sync(awaitable, self._should_await({})) # type: ignore
return a_sync_property_wrap
47 changes: 47 additions & 0 deletions a_sync/_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

import asyncio
from inspect import getfullargspec
from typing import Awaitable, Callable, Literal, TypeVar, Union, overload

from async_property.base import AsyncPropertyDescriptor
from async_property.cached import AsyncCachedPropertyDescriptor

T = TypeVar("T")

_flag_name_options = 'sync', 'asynchronous'


def _validate_wrapped_fn(fn: Callable) -> None:
"""Ensures 'fn' is an appropriate function for wrapping with a_sync."""
if isinstance(fn, (AsyncPropertyDescriptor, AsyncCachedPropertyDescriptor)):
return # These are always valid
if not asyncio.iscoroutinefunction(fn):
raise TypeError(f"{fn} must be a coroutine function.")
fn_args = getfullargspec(fn)[0]
for flag in _flag_name_options:
if flag in fn_args:
raise RuntimeError(f"{fn} must not have any arguments with the following names: {_flag_name_options}")


@overload
def _await_if_sync(awaitable: Awaitable[T], sync: Literal[True]) -> T:
...

@overload
def _await_if_sync(awaitable: Awaitable[T], sync: Literal[False]) -> Awaitable[T]:
...

def _await_if_sync(awaitable: Awaitable[T], sync: bool) -> Union[T, Awaitable[T]]:
"""
If 'sync' is True, awaits the awaitable and returns the return value.
If 'sync' is False, simply returns the awaitable.
"""
if sync:
try:
return asyncio.get_event_loop().run_until_complete(awaitable)
except RuntimeError as e:
if "is already running" in str(e):
raise RuntimeError(str(e), f"You may want to make this an async function by setting one of the following kwargs: {_flag_name_options}")
raise
else:
return awaitable
23 changes: 23 additions & 0 deletions a_sync/_meta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

from asyncio import iscoroutinefunction

from async_property.base import AsyncPropertyDescriptor
from async_property.cached import AsyncCachedPropertyDescriptor

from a_sync import _bound


class ASyncMeta(type):
"""Any class with metaclass ASyncMeta will have its functions wrapped with a_sync upon class instantiation."""
def __new__(cls, name, bases, attrs):
for attr_name, attr_value in attrs.items():
# Special handling for functions decorated with async_property and async_cached_property
if isinstance(attr_value, (AsyncPropertyDescriptor, AsyncCachedPropertyDescriptor)):
print(attr_name)
print(attrs[attr_name])
attrs[attr_name] = _bound.a_sync_property(attr_value)
print(attrs[attr_name])
elif iscoroutinefunction(attr_value):
# NOTE We will need to improve this logic if somebody needs to use it with classmethods or staticmethods.
attrs[attr_name] = _bound.a_sync(attr_value)
return super(ASyncMeta, cls).__new__(cls, name, bases, attrs)
21 changes: 21 additions & 0 deletions a_sync/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

from a_sync import _helpers
from a_sync._meta import ASyncMeta

class ASyncBase(metaclass=ASyncMeta):
"""Inherit from this class to a-syncify all of your bound methods."""
pass

def _should_await(self, kwargs: dict) -> bool:
"""Returns a boolean that indicates whether methods of 'instance' should be called as sync or async methods."""
for flag in _helpers._flag_name_options:
try:
sync = kwargs[flag] if flag in kwargs else getattr(self, flag)
except AttributeError:
continue
assert isinstance(sync, bool), f"{flag} must be boolean. You passed {sync}."
if flag == 'asynchronous':
# must invert
return not sync
return sync
raise RuntimeError(f"{self} must have one of the following properties to tell a_sync how to proceed: {_helpers._flag_name_options}")
34 changes: 34 additions & 0 deletions a_sync/decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

import functools
from typing import Callable, TypeVar

from typing_extensions import ParamSpec # type: ignore

from a_sync import _helpers

P = ParamSpec("P")
T = TypeVar("T")


def a_sync(coro_fn: Callable[P, T]) -> Callable[P, T]: # type: ignore
f"""
A coroutine function decorated with this decorator can be called as a sync function by passing a boolean value for any of these kwargs: {_helpers._flag_name_options}
"""

_helpers._validate_wrapped_fn(coro_fn)

@functools.wraps(coro_fn)
def a_sync_wrap(*args: P.args, **kwargs: P.kwargs) -> T: # type: ignore
# If a flag was specified in the kwargs, we will defer to it.
for flag in _helpers._flag_name_options:
if flag in kwargs:
val = kwargs.pop(flag)
if not isinstance(val, bool):
raise TypeError(f"'{flag}' must be boolean. You passed {val}.")
return _helpers._await_if_sync( # type: ignore
coro_fn(*args, **kwargs),
val if flag == 'sync' else not val
)
# No flag specified in the kwargs, we will just return the awaitable.
return coro_fn(*args, **kwargs)
return a_sync_wrap
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
async_property==0.2.1
typing_extensions>=0.4.0
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[metadata]
description-file = README.md
24 changes: 24 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from setuptools import find_packages, setup

with open("requirements.txt", "r") as f:
requirements = list(map(str.strip, f.read().split("\n")))[:-1]

setup(
name='a-sync',
packages=find_packages(),
use_scm_version={
"root": ".",
"relative_to": __file__,
"local_scheme": "no-local-version",
"version_scheme": "python-simplified-semver",
},
description='A library that makes it easy to define objects that can be used for both sync and async use cases.',
author='BobTheBuidler',
author_email='[email protected]',
url='https://github.com/BobTheBuidler/a-sync',
license='MIT',
install_requires=requirements,
setup_requires=[
'setuptools_scm',
],
)
Empty file added tests/__init__.py
Empty file.
4 changes: 4 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

import sys, os

sys.path.insert(0, os.path.abspath('.'))
18 changes: 18 additions & 0 deletions tests/fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from a_sync import ASyncBase
from async_property import async_property, async_cached_property

class TestClass(ASyncBase):
def __init__(self, sync: bool):
self.sync = sync

async def test_fn(self) -> int:
return 2

@async_property
async def test_property(self) -> int:
return 4

@async_cached_property
async def test_cached_property(self) -> int:
return 6

26 changes: 26 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@

import asyncio
import inspect

from tests.fixtures import TestClass

def _await(coro):
return asyncio.get_event_loop().run_until_complete(coro)

def test_base_sync():
sync_instance = TestClass(True)
assert sync_instance.test_fn() == 2
assert sync_instance.test_property == 4
assert sync_instance.test_cached_property == 6

# Can we override with kwargs?
assert inspect.isawaitable(sync_instance.test_fn(sync=False))

def test_base_async():
async_instance = TestClass(False)
assert _await(async_instance.test_fn()) == 2
assert _await(async_instance.test_property) == 4
assert _await(async_instance.test_cached_property) == 6

# Can we override with kwargs?
assert isinstance(async_instance.test_fn(sync=True), int)
13 changes: 13 additions & 0 deletions tests/test_decorator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@

import asyncio

import a_sync

@a_sync.a_sync
async def some_test_fn() -> int:
return 2

def test_decorator():
assert asyncio.get_event_loop().run_until_complete(some_test_fn()) == 2
assert some_test_fn(sync=True) == 2
assert some_test_fn(asynchronous=False) == 2

0 comments on commit 8826d0d

Please sign in to comment.