14

我有这个包:

mypackage/
    __init__.py
    a.py
    b.py

而且我想将模块a中的东西导入模块b,在模块b中编写是否有意义

from mypackage.a import *

还是我应该使用

from a import *

两个选项都可以,我只是想知道哪个更好(第二个有意义,因为它在同一级别,但我正在考虑第一个以避免冲突,例如,如果系统从包含名为的文件的文件夹运行a.py)。

4

2 回答 2

7

您可以安全地使用数字 2,因为不应该有任何冲突 - 您将始终从与当前包相同的包中导入模块。请注意,如果您的模块与标准库模块之一具有相同的名称,它将被导入而不是标准模块。从文档

当一个名为的模块spam被导入时,解释器首先搜索一个具有该名称的内置模块。spam.py如果没有找到,它会在由变量 给出的目录列表中搜索一个文件sys.pathsys.path从这些位置初始化:

  • 包含输入脚本的目录(或当前目录)。
  • PYTHONPATH(目录名称列表,语法与
  • 壳变量PATH)。
  • 安装相关的默认值。

初始化后,Python 程序可以修改sys.path. 包含正在运行的脚本的目录位于搜索路径的开头,位于标准库路径之前。这意味着将加载该目录中的脚本,而不是库目录中的同名模块。除非打算更换,否则这是一个错误。有关详细信息,请参阅标准模块部分。

该选项from mypackage.a import *可用于整个项目的一致性原因。在某些模块中,无论如何您都必须进行绝对导入。因此,您不必考虑模块是否在同一个包中,只需在整个项目中使用统一的样式。此外,这种方法更可靠和可预测。

Python 风格指南不推荐使用相对导入:

非常不鼓励用于包内导入的相对导入。始终对所有导入使用绝对包路径。即使现在 PEP 328已在 Python 2.5 中完全实现,它的显式相对导入风格也被积极劝阻。绝对导入更便携,通常更具可读性。

从 python 2.5开始,引入了包内相对导入的新语法。现在您.可以引用当前模块并..引用上面1级的模块。

from . import echo
from .. import formats
from ..filters import equalizer
于 2012-08-14T12:11:26.100 回答
5

你应该使用from mypackage.a import things, you, want.

There are two issues here, the main one is relative vs absolute imports, the semantics of which changed in Python 3, and can optionally be used in Python 2.6 and 2.7 using a __future__ import. By using mypackage.a you guarantee that you will get the code you actually want, and it will work reliably on future versions of Python.

The second thing is that you should avoid import *, as it can potentially mask other code. What if the a.py file gained a function called sum? It would silently override the builtin one. This is especially bad when importing your own code in other modules, as you may well have reused variable or function names.

Therefore, you should only ever import the specific functions you need. Using pyflakes on your sourcecode will then warn you when you have potential conflicts.

于 2012-08-14T12:15:40.043 回答