common.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:ormeasy 作者: spoqa 项目源码 文件源码
def get_all_modules(
    module_name: str, path: typing.Optional[typing.Sequence[str]]=None,
) -> typing.AbstractSet[str]:
    """Find all module names from given ``module_name``.

    :param str module_name: The name of root module which want to find.
    :param list[str] or None path: The path to find the root module.
    :return: The set of module names.

    .. code-block:: python

       >>> get_all_modules('ormeasy')
       {'ormeasy.alembic', 'ormeasy.common', 'ormeasy.sqlalchemy'}
       >>> get_all_modules('ormeasy.common')
       {'ormeasy.common'}

    """
    root_mod, *_ = module_name.split('.')
    module_spec = importlib.machinery.PathFinder.find_spec(root_mod, path)
    if not module_spec:
        if path:
            raise ValueError(
                '{!s} inexists or is not a python module in {!s}'.format(
                    root_mod, path
                )
            )
        raise ValueError(
            '{!s} inexists or is not a python module'.format(root_mod)
        )
    module_name_with_dot = root_mod + '.'
    if module_spec.submodule_search_locations:
        module_names = {
            name
            for _, name, _ in pkgutil.walk_packages(
                module_spec.submodule_search_locations,
                prefix=module_name_with_dot
            )
        }
    else:
        module_names = {
            name
            for _, name, _ in pkgutil.walk_packages(
                [os.path.dirname(module_spec.origin)]
            )
            if name.startswith(module_name_with_dot) or name == module_name
        }
    return {m for m in module_names if m.startswith(module_name)}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号