Skip to content

alicebot.utils

AliceBot 内部使用的实用工具。

class ModulePathFinder

Bases: importlib.abc.MetaPathFinder

用于查找 AliceBot 组件的元路径查找器。

  • Attributes

    • path (ClassVar[list[str]])

method find_spec(self, fullname, path = None, target = None)

用于查找指定模块的 spec

  • Arguments

    • fullname (str)

    • path (collections.abc.Sequence[str] | None)

    • target (module | None)

  • Returns

    Type: _frozen_importlib.ModuleSpec | None

function is_config_class(config_class)

判断一个对象是否是配置类。

  • Arguments

    • config_class (Any) - 待判断的对象。
  • Returns

    Type: typing_extensions.TypeIs[type[alicebot.config.ConfigModel]]

    返回是否是配置类。

function get_classes_from_module(module, super_class)

从模块中查找指定类型的类。

  • Arguments

    • module (module) - Python 模块。

    • super_class (~_TypeT) - 要查找的类的超类。

  • Returns

    Type: list[~_TypeT]

    返回符合条件的类的列表。

function get_classes_from_module_name(name, super_class, *, reload = False)

从指定名称的模块中查找指定类型的类。

  • Arguments

    • name (str) - 模块名称,格式和 Python import 语句相同。

    • super_class (~_TypeT) - 要查找的类的超类。

    • reload (bool) - 是否重新加载模块。

  • Returns

    Type: list[tuple[~_TypeT, module]]

    返回由符合条件的类和模块组成的元组的列表。

  • Raises

    • ImportError - 当导入模块过程中出现错误。

class PydanticEncoder

Bases: json.encoder.JSONEncoder

用于解析 pydantic.BaseModelJSONEncoder 类。

method default(self, o)

Implement this method in a subclass such that it returns

a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this::

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
  • Arguments

    • o (Any)
  • Returns

    Type: Any

function samefile(path1, path2)

一个 os.path.samefile 的简单包装。

  • Arguments

    • path1 (str | bytes | os.PathLike[str] | os.PathLike[bytes]) - 路径 1。

    • path2 (str | bytes | os.PathLike[str] | os.PathLike[bytes]) - 路径 2。

  • Returns

    Type: bool

    如果两个路径是否指向相同的文件或目录。

function sync_ctx_manager_wrapper(cm)

将同步上下文管理器包装为异步上下文管理器。

  • Arguments

    • cm (contextlib.AbstractContextManager[~_T]) - 待包装的同步上下文管理器。

    • to_thread - 是否在独立的线程中运行同步函数。默认为 False

  • Returns

    Type: collections.abc.AsyncGenerator[~_T, None]

    异步上下文管理器。

async function async_map(tg, func, iterable)

在 TaskGroup 中并行运行多个任务并且获取其结果。

注意:结果将不会按照参数给出的顺序返回,而是按照实际执行结束的顺序返回。 为了将结果和参数对应起来,这个函数返回的生成器的每一项将是一个由参数和结果组成的元组。

  • Arguments

    • tg (anyio.abc.TaskGroup) - 运行任务的 TaskGroup。

    • func (collections.abc.Callable[[~_T], collections.abc.Awaitable[~_R]]) - 并行运行的函数。

    • iterable (collections.abc.Iterable[~_T]) - 并行运行的函数的参数。

  • Returns

    Type: collections.abc.AsyncGenerator[tuple[~_T, ~_R]]

    由参数和结果组成元组的生成器。

Released under the MIT License.