【问题标题】:Calling Python function that requires libraries from another file调用需要来自另一个文件的库的 Python 函数
【发布时间】:2019-01-25 05:39:46
【问题描述】:

我有一个名为“custom_functions.py”的脚本,其中包含我为简化工作而编写的函数。每个自定义函数调用不同的库。 “custom_functions.py”看起来像这样:

# This is custom_functions.py
import pandas as pd
import numpy as np

def create_df():
   return pd.DataFrame({'a': [1, 2, 3]})

def create_array():
   return np.array([1, 2, 3])

在过去的几个月里,随着我向 custom_functions.py 添加了函数,我需要导入越来越多的库才能将脚本调用到另一个文件中(我们称之为“main.py ”)。当我最终只需要一个时,为所有函数加载库似乎效率低下/不必要。

有没有办法只调用例如create_array 不需要同时加载create_df 所需的库?例如,如果我可以删除 custom_functions.py 中的所有库调用,并且在从 custom_functions.py 调用特定函数之前只在 main.py 中导入必要的库,那将是理想的,例如:

# This is the proposed custom_functions.py
def create_df():
   return pd.DataFrame({'a': [1, 2, 3]})

def create_array():
   return np.array([1, 2, 3])

# This is the proposed main.py
import numpy as np
from custom_functions import create_array

上面的代码抛出一个错误(NameError: name "np" is not defined)。将 custom_functions.py 分解为单独的脚本并在每次将 custom_functions 加载到 main.py 时只加载所有关联库的唯一解决方案是什么?

如果有帮助,我在 Windows 10 机器上使用 Python 3.6.5 和 Anaconda。

感谢您的帮助!

【问题讨论】:

  • 建议:也许将导入移动到函数内部?

标签: python


【解决方案1】:

正确的方法是将其拆分为不同的文件。

如果您真的不想这样做,您可以将任何导入放入函数中。这样做的缺点是每次调用函数时,模块都会再次导入,而不是只导入一次。如果您这样做,请尽可能绝对具体。

def create_array():
    from numpy import array
    return array([1, 2, 3])

【讨论】:

    【解决方案2】:

    您可以按照@ParitoshSingh 的建议移动导入,但一般最佳实践鼓励将导入保留在文件的顶部,除非您有特定的理由不这样做。现在这似乎没有必要,但随着函数复杂性的增加,您可能会遇到循环导入问题以及通常很难调试/解决的意外命名空间问题。

    如果它对你来说真的很重要,那么你应该将你的实用程序函数拆分到不同的文件中。

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 2017-03-27
      • 2014-03-29
      相关资源
      最近更新 更多