【发布时间】: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