Python:如何导入与子包同名的模块?

标签 python import module

我还没有遇到这个问题,但我很好奇如何导入与子包同名的模块。例如,一个可能的模块结构可能如下所示:

mymodule\
    __init__.py
    string.py

现在,如果我需要 mymodule.string 子包 string 模块,每个 Python 发行版都从一个包中提供是否在同一目录下,例如 __init__.py?以下代码行全部导入子包。

from   .                import string
import mymodule.string  as string
import string

最佳答案

在 Python 2.5 或 2.6 中,您可以使用:

>>> from __future__ import absolute_import

这告诉 Python,所有不是明确相对的导入都应该被视为绝对的。即,在使用此声明后,您可以使用以下方式访问内置字符串模块和您自己的字符串模块:

>>> import string as the_builtin_string_module
>>> from . import string as my_package_string_module

我相信这将成为 Python 2.7(和 Python 3.0)中的默认设置。

有关详细信息,请参阅:http://www.python.org/dev/peps/pep-0328/#rationale-for-absolute-imports

关于Python:如何导入与子包同名的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9384969/

相关文章:

python - 为什么导入内部函数时会出现UnboundLocalError

import - 在 TypeScript 中动态导入模块

php - 我如何使用每个模块 Bootstrap ?

python - 如何在python中存储绝对路径并将其显示为目录结构?

python - 将条目添加到 SQLAlchemy 数据库触发器 `sqlite InterfaceError: Error binding parameter 0 - probably unsupported type`

c# - VS2017 C# 导入 WinForms 生成命名空间错误

python - 将某些功能拆分为函数、模块和包的推荐方法?

python - 如何在 PyOpenGL 中使用 glBufferData()?

c# - 连接到 Com5 : System. NullReferenceException 未处理

XML 架构 : how to reference a type from a no namespace XSD