Python中的惰性导入

2025年1月4日 | 阅读 4 分钟

懒加载导入是 Pyforest 模块的一项功能,它允许用户在不将库添加到程序的情况下执行任务,因为库已添加到代码片段中。它专为那些厌倦了在程序中编写导入语句的用户而设计。当程序员需要编写长代码时,懒加载导入非常有用。

为什么需要懒加载导入?

一些 Python 用户经常会遇到在每个程序中导入多个模块的问题,例如 NumPy、pandas、sklearn、os、sys、pickle、nltk 等,这可能是一项令人烦恼且恼人的任务,因为程序员的工作没有带来任何好处,反而浪费了时间,如果程序员某次忘记在程序中导入任何模块,程序就会引发错误,而程序员不希望因为模块而导致程序崩溃。

因此,为了解决这个问题,Pyforest 提供了一个解决方案,它通过创建一个内置函数,其中包含 Python 99% 流行模块的详细信息,识别我们正在使用的导入,并自动添加模块,因此无需一次又一次地导入模块。通过这样做,编写代码/程序可以更轻松、更快,并且可以在不同的程序中使用预安装的模块,而无需导入它们。它也不会添加所有模块。它会检查程序,并且只添加在程序中反复使用的那些模块。

让我们看一个简单的代码

代码

输出

 
Traceback (most recent call last):
  File "c:\Users\Username\OneDrive\Desktop\javatpoint\May\main.py", line 4, in <module>
    array = np.array([1,2,3])
NameError: name 'np' is not defined   

说明

在上面的代码中,由于未导入 NumPy 模块,因此会引发错误。

要解决上述问题,我们可以通过键入以下命令来安装 Pyforest 模块:

pip install pyforest

上述命令安装了 pyforest 模块,用于懒加载导入和处理上述问题。

如果命令提示符中看到类似这样的输出,则表明 pyforest 模块已成功安装在系统中。

输出

 
WARNING: Ignoring invalid distribution -matplotlib (c:\users\username\appdata\local\programs\python\python39\lib\site-packages)
Collecting pyforest
  Downloading pyforest-1.1.0.tar.gz (15 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: pyforest
  Building wheel for pyforest (setup.py) ... done
  Created wheel for pyforest: filename=pyforest-1.1.0-py2.py3-none-any.whl size=14633 sha256=0b97c41e0440c8f221bee2fdc4d29b2eb521c7ae254fd4f713747b36d8d8270c
  Stored in directory: c:\users\username\appdata\local\pip\cache\wheels\d5\1a\3e\6193fe1c56168f5df4aef57d8411033ba4611881135d495727
Successfully built pyforest
WARNING: Ignoring invalid distribution -matplotlib (c:\users\username\appdata\local\programs\python\python39\lib\site-packages)
Installing collected packages: pyforest
Successfully installed pyforest-1.1.0   

让我们看看如何导入 pyforest 模型提供的 lazy_modules,并打印所有可用的模块。

代码

输出

 
['import pickle', 'import statistics', 'import imutils', 'import cv2', 'import tensorflow as tf', 'import tqdm', 'import nltk', 'from pathlib import Path', 'from sklearn.linear_model import ElasticNetCV', 'import sklearn', 'from xlrd import open_workbook', 'import plotly.graph_objs as go', 'import re', 'from sklearn import svm', 'from sklearn.model_selection import StratifiedKFold', 'import torch', 'from sklearn.feature_extraction.text import CountVectorizer', 'from sklearn.model_selection import KFold', 'import altair as alt', 'from sklearn.ensemble import RandomForestRegressor', 'from sklearn.preprocessing import StandardScaler', 'import textblob', 'import dash', 'from sklearn.model_selection import GridSearchCV', 'from sklearn import metrics', 'import spacy', 'from sklearn.preprocessing import MinMaxScaler', 'import awswrangler as wr', 'import keras', 'import matplotlib as mpl', 'from sklearn.impute import SimpleImputer', 'from sklearn.linear_model import RidgeCV', 'from sklearn.model_selection import train_test_split', 'from sklearn.cluster import KMeans', 'from sklearn.manifold import TSNE', 'import fastai', 'import plotly as py', 'from sklearn.preprocessing import OneHotEncoder', 'from sklearn.model_selection import cross_val_score', 'from sklearn.model_selection import RandomizedSearchCV', 'from PIL import Image', 'from sklearn.ensemble import GradientBoostingRegressor', 'import statsmodels.api as sm', 'from sklearn.linear_model import LassoCV', 'from pyspark import SparkContext', 'import seaborn as sns', 'from sklearn.ensemble import GradientBoostingClassifier', 'from sklearn.decomposition import PCA', 'import matplotlib.pyplot as plt', 'from scipy import signal as sg', 'import os', 'import lightgbm as lgb', 'from scipy import stats', 'import numpy as np', 'from sklearn.preprocessing import RobustScaler', 'import fbprophet', 'import pandas as pd', 'import glob', 'import bokeh', 'from sklearn.linear_model import ElasticNet', 'from sklearn.linear_model import Lasso', 'from sklearn.feature_extraction.text import TfidfVectorizer', 'from sklearn.linear_model import LinearRegression', 'import skimage', 'from sklearn.linear_model import Ridge', 'from fbprophet import Prophet', 'from dask import dataframe as dd', 'import plotly.express as px', 'from statsmodels.tsa.arima_model import ARIMA', 'import xgboost as xgb', 'import datetime as dt', 'from openpyxl import load_workbook', 'import pydot', 'from sklearn.ensemble import RandomForestClassifier', 'from sklearn.preprocessing import LabelEncoder', 'import gensim', 'from sklearn.linear_model import LogisticRegression', 'from sklearn.preprocessing import PolynomialFeatures', 'import sys']   

说明

在上面的代码中,导入了 pyforest 模块,并通过 lazy_imports() 函数将所有模块作为列表导入。

让我们看另一个例子

代码

输出

Lazy Import in Python
 
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
<IPython.core.display.Javascript object>
import matplotlib.pyplot as plt
import numpy as np
['import matplotlib.pyplot as plt', 'import numpy as np']   

说明

在上面的代码中,使用 numpy 模块创建了一个数组,并绘制了该数组。模块未被导入。相反,它们是从 pyforest 模块中调用的。

懒加载导入在自动导入库方面非常有用,这是 Pyforest 库的一项有用功能。如果库未被使用,则不会添加它。