如何使用两个脚本更好地导入 python 模块?

How can I better import python modules with two scripts?

假设我有两个脚本:functions.pyalgorithm.py。在前者中,我编写了在后者中导入的函数,即终端中 运行 的脚本。

所以我在 algorithms.py 中的脚本如下所示:

import functions
x = functions.a_function()

例如,如果我在 a_function() 中使用了 numpy,但我没有在 algorithm.py 中的其他地方使用它,我应该在 functions.py 或 algorithm.py 中导入 numpy (或两者)?

由于我在 python 方面缺乏经验,我想知道人们通常是如何解决这个特定问题的。

非常感谢。

总是在你使用它的地方导入一个模块。

如果 functions.py 中的函数使用 numpy,请将其导入那里;如果 algorithms.py 中的人使用它,请将其导入那里。如果两者都这样做,请在两个地方导入它。

自己试一下。

如果你在 functions.py 中使用 numpy,你 需要 在 functions.py 中导入它(这与实践的好坏无关,如果你不't,它甚至不会工作)并且没用将它导入algorithm.py。