Python:如何导入与子包具有相同名称的模块? [英] Python: how to import a module which has the same name as a subpackage?

查看:144
本文介绍了Python:如何导入与子包具有相同名称的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I haven't come across this problem yet, but I'm curious about how to import a module that has the same name as a sub-package. For instance, a possible module-structure could look like this:

mymodule\
    __init__.py
    string.py

现在,如果我需要 mymodule.string subpackage 字符串模块,它与同一目录中的每个Python发行版一起提供,例如 __初始化__。PY ?以下代码行 all 导入子包。

Now, what if I need the mymodule.string subpackage and the string module that is delivered with every Python distribution from a package that is within the same directory, such as __init__.py? The following lines of code all import the subpackage.

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


推荐答案

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

In Python 2.5 or 2.6, you can use:

>>> from __future__ import absolute_import

告诉Python所有非明确相关的导入都应视为绝对值。即,在使用此声明之后,您可以使用以下命令访问内置字符串模块和您自己的字符串模块:

Which tells Python that all imports that aren't explicitly relative should be treated as absolute. I.e., after using this declaration, you can access both the builtin string module and your own string module using:

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

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

I believe that this becomes the default in Python 2.7 (and Python 3.0).

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

For more info, see: http://www.python.org/dev/peps/pep-0328/#rationale-for-absolute-imports

这篇关于Python:如何导入与子包具有相同名称的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆