python27默认情况下导入不应该是绝对的吗? [英] Shouldn't the imports be absolute by default in python27?
问题描述
想象一下目录结构:
/
a/
__init__.py
b.py
c.py
c.py
文件 /a/b.py
看起来像:
import c
should_be_absolute = c
所有其他文件(包括 __ init __
)都是空的。
All the other files (including __init__
) are empty.
运行测试脚本时(使用python 2.7):
When running a test script (using python 2.7):
import a.b
print a.b.should_be_absolute
来自空目录的 PYTHONPATH = /
(所以没有添加任何内容从当前目录到 PYTHONPATH
我得到了
with PYTHONPATH=/
from an empty directory (so nothing is added to PYTHONPATH
from current directory) I get
<module 'a.c' from '/a/c.py'>
根据 PEP 328 和声明 import<>总是绝对的
我希望:
<module 'c' from '/c.py'>
当我删除 /a/c.py时输出是预期的
file。
我缺少什么?如果这是正确的行为 - 如何从 b
导入 c
模块(而不是 ac
)?
What am I missing? And if this is the correct behavior - how to import the c
module from b
(instead of a.c
)?
更新:
根据 python dev邮件列表它似乎是文档中的错误。在python27中,默认导入为不绝对。
According to python dev mailing list it appears to be a bug in the documentation. The imports are not absolute by default in python27.
推荐答案
您需要添加 from __future__ import absolute_import
或在Python 2.7上使用 importlib.import_module('c')
you need to add from __future__ import absolute_import
or use importlib.import_module('c')
on Python 2.7
这是Python 3的默认设置。
It is default on Python 3.
Python中存在一个错误: __ future __。py
及其文档声明绝对导入在2.7中是强制性的,但它们没有。
There was a bug in Python: __future__.py
and its documentation claim absolute imports became mandatory in 2.7, but they didn't.
这篇关于python27默认情况下导入不应该是绝对的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!