🎨 format code using black and isort

This commit is contained in:
yanyongyu
2021-11-22 23:21:26 +08:00
parent 602185a34e
commit a98d98cd12
86 changed files with 2893 additions and 2095 deletions

View File

@ -9,13 +9,13 @@ from typing import Iterable
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
del pkg_resources
except ImportError:
import pkgutil
__path__: Iterable[str] = pkgutil.extend_path(
__path__, # type: ignore
__name__)
__path__: Iterable[str] = pkgutil.extend_path(__path__, __name__) # type: ignore
del pkgutil
except Exception:
pass

View File

@ -15,7 +15,6 @@ if TYPE_CHECKING:
class _ApiCall(Protocol):
async def __call__(self, **kwargs: Any) -> Any:
...
@ -146,7 +145,8 @@ class Bot(abc.ABC):
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running CallingAPI hook. "
"Running cancelled!</bg #f8bbd0></r>")
"Running cancelled!</bg #f8bbd0></r>"
)
exception = None
result = None
@ -157,8 +157,8 @@ class Bot(abc.ABC):
exception = e
coros = list(
map(lambda x: x(self, exception, api, data, result),
self._called_api_hook))
map(lambda x: x(self, exception, api, data, result), self._called_api_hook)
)
if coros:
try:
logger.debug("Running CalledAPI hooks...")
@ -166,16 +166,17 @@ class Bot(abc.ABC):
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running CalledAPI hook. "
"Running cancelled!</bg #f8bbd0></r>")
"Running cancelled!</bg #f8bbd0></r>"
)
if exception:
raise exception
return result
@abc.abstractmethod
async def send(self, event: "Event", message: Union[str, "Message",
"MessageSegment"],
**kwargs) -> Any:
async def send(
self, event: "Event", message: Union[str, "Message", "MessageSegment"], **kwargs
) -> Any:
"""
:说明:

View File

@ -2,9 +2,8 @@ import abc
from pydantic import BaseModel
from nonebot.utils import DataclassEncoder
from ._message import Message
from nonebot.utils import DataclassEncoder
class Event(abc.ABC, BaseModel):

View File

@ -1,8 +1,17 @@
import abc
from copy import deepcopy
from dataclasses import field, asdict, dataclass
from typing import (Any, Dict, List, Type, Union, Generic, Mapping, TypeVar,
Iterable)
from typing import (
Any,
Dict,
List,
Type,
Union,
Generic,
Mapping,
TypeVar,
Iterable,
)
from ._template import MessageTemplate
@ -14,6 +23,7 @@ TM = TypeVar("TM", bound="Message")
@dataclass
class MessageSegment(Mapping, abc.ABC, Generic[TM]):
"""消息段基类"""
type: str
"""
- 类型: ``str``
@ -82,11 +92,12 @@ class MessageSegment(Mapping, abc.ABC, Generic[TM]):
class Message(List[TMS], abc.ABC):
"""消息数组"""
def __init__(self: TM,
message: Union[str, None, Mapping, Iterable[Mapping], TMS, TM,
Any] = None,
*args,
**kwargs):
def __init__(
self: TM,
message: Union[str, None, Mapping, Iterable[Mapping], TMS, TM, Any] = None,
*args,
**kwargs,
):
"""
:参数:
@ -103,8 +114,7 @@ class Message(List[TMS], abc.ABC):
self.extend(self._construct(message))
@classmethod
def template(cls: Type[TM],
format_string: Union[str, TM]) -> MessageTemplate[TM]:
def template(cls: Type[TM], format_string: Union[str, TM]) -> MessageTemplate[TM]:
"""
:说明:
@ -156,8 +166,7 @@ class Message(List[TMS], abc.ABC):
@staticmethod
@abc.abstractmethod
def _construct(
msg: Union[str, Mapping, Iterable[Mapping], Any]) -> Iterable[TMS]:
def _construct(msg: Union[str, Mapping, Iterable[Mapping], Any]) -> Iterable[TMS]:
raise NotImplementedError
def __add__(self: TM, other: Union[str, Mapping, Iterable[Mapping]]) -> TM:

View File

@ -1,8 +1,21 @@
import inspect
import functools
from string import Formatter
from typing import (TYPE_CHECKING, Any, Set, List, Type, Tuple, Union, Generic,
Mapping, TypeVar, Sequence, cast, overload)
from typing import (
TYPE_CHECKING,
Any,
Set,
List,
Type,
Tuple,
Union,
Generic,
Mapping,
TypeVar,
Sequence,
cast,
overload,
)
if TYPE_CHECKING:
from . import Message, MessageSegment
@ -15,14 +28,15 @@ class MessageTemplate(Formatter, Generic[TF]):
"""消息模板格式化实现类"""
@overload
def __init__(self: "MessageTemplate[str]",
template: str,
factory: Type[str] = str) -> None:
def __init__(
self: "MessageTemplate[str]", template: str, factory: Type[str] = str
) -> None:
...
@overload
def __init__(self: "MessageTemplate[TM]", template: Union[str, TM],
factory: Type[TM]) -> None:
def __init__(
self: "MessageTemplate[TM]", template: Union[str, TM], factory: Type[TM]
) -> None:
...
def __init__(self, template, factory=str) -> None:
@ -51,15 +65,15 @@ class MessageTemplate(Formatter, Generic[TF]):
elif isinstance(self.template, self.factory):
template = cast("Message[MessageSegment]", self.template)
for seg in template:
msg += self.vformat(str(seg), args,
kwargs) if seg.is_text() else seg
msg += self.vformat(str(seg), args, kwargs) if seg.is_text() else seg
else:
raise TypeError('template must be a string or instance of Message!')
raise TypeError("template must be a string or instance of Message!")
return msg
def vformat(self, format_string: str, args: Sequence[Any],
kwargs: Mapping[str, Any]) -> TF:
def vformat(
self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]
) -> TF:
used_args = set()
result, _ = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(list(used_args), args, kwargs)
@ -79,8 +93,9 @@ class MessageTemplate(Formatter, Generic[TF]):
results: List[Any] = []
for (literal_text, field_name, format_spec,
conversion) in self.parse(format_string):
for (literal_text, field_name, format_spec, conversion) in self.parse(
format_string
):
# output the literal text
if literal_text:
@ -96,14 +111,16 @@ class MessageTemplate(Formatter, Generic[TF]):
if auto_arg_index is False:
raise ValueError(
"cannot switch from manual field specification to "
"automatic field numbering")
"automatic field numbering"
)
field_name = str(auto_arg_index)
auto_arg_index += 1
elif field_name.isdigit():
if auto_arg_index:
raise ValueError(
"cannot switch from manual field specification to "
"automatic field numbering")
"automatic field numbering"
)
# disable auto arg incrementing, if it gets
# used later on, then an exception will be raised
auto_arg_index = False
@ -132,8 +149,10 @@ class MessageTemplate(Formatter, Generic[TF]):
formatted_text = self.format_field(obj, str(format_control))
results.append(formatted_text)
return self.factory(functools.reduce(self._add, results or
[""])), auto_arg_index
return (
self.factory(functools.reduce(self._add, results or [""])),
auto_arg_index,
)
def format_field(self, value: Any, format_spec: str) -> Any:
if issubclass(self.factory, str):
@ -142,11 +161,20 @@ class MessageTemplate(Formatter, Generic[TF]):
segment_class: Type[MessageSegment] = self.factory.get_segment_class()
method = getattr(segment_class, format_spec, None)
method_type = inspect.getattr_static(segment_class, format_spec, None)
return (super().format_field(value, format_spec) if
((method is None) or
(not isinstance(method_type, (classmethod, staticmethod))
) # Only Call staticmethod or classmethod
) else method(value)) if format_spec else value
return (
(
super().format_field(value, format_spec)
if (
(method is None)
or (
not isinstance(method_type, (classmethod, staticmethod))
) # Only Call staticmethod or classmethod
)
else method(value)
)
if format_spec
else value
)
def _add(self, a: Any, b: Any) -> Any:
try: