python27默认情况下导入不应该是绝对的吗?

编程入门 行业动态 更新时间:2024-10-11 21:22:41
本文介绍了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默认情况下导入不应该是绝对的吗?

本文发布于:2023-11-03 21:32:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不应   情况下

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!