nonebot2/nonebot/utils.py

31 lines
754 B
Python
Raw Normal View History

2020-08-10 13:06:02 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
2020-08-14 17:41:24 +08:00
import asyncio
2020-08-10 13:06:02 +08:00
import dataclasses
2020-08-14 17:41:24 +08:00
from functools import wraps, partial
2020-08-10 13:06:02 +08:00
2020-08-14 17:41:24 +08:00
from nonebot.typing import Any, Callable, Awaitable, overrides
def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]:
@wraps(func)
async def _wrapper(*args: Any, **kwargs: Any) -> Any:
loop = asyncio.get_running_loop()
pfunc = partial(func, *args, **kwargs)
result = await loop.run_in_executor(None, pfunc)
return result
return _wrapper
2020-08-10 13:06:02 +08:00
class DataclassEncoder(json.JSONEncoder):
@overrides(json.JSONEncoder)
def default(self, o):
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
return super().default(o)