调用需要来自另一个文件的库的Python函数

时间:2019-01-24 21:31:13

标签: python

我有一个名为“ 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中的所有库调用,并且仅在main.py中导入必要的库,然后再从custom_functions.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加载到main.py中时,将custom_functions.py分解为单独的脚本并仅加载所有关联的库吗?

如果有帮助,我将在Windows 10计算机上将Python 3.6.5与Anaconda结合使用。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

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

如果这对您确实很重要,则应将实用程序功能拆分为不同的文件。

相关问题