Lazy Import in Python

Lazy import is a Pyforest Module feature that allows users to execute the task without adding libraries to the program as the libraries are added to the code snippet. It was built for those users who are tired of writing those import statements in the program. Lazy import is very helpful for programmers when they need to write length codes.

Why is Lazy Import Needed?

Some a Python user often face the problem of importing multiple modules such as NumPy, pandas, sklearn, os, sys, pickle, nltk and many more in each program, which can be annoying task and irritating as programmers are doing work with no benefit, rather they are wasting time and if any time the programmer forgot to import any module in the program then an error is raised by the program and programmers don't want crash the program just because of the modules.

So, to handle this problem, Pyforest comes with a solution of this problem by creating a built-in function having details of 99% of the popular modules of Python identifying the imports we are using and automatically adding the module, so it is not required to import the module again and again. By doing this, it can be easier and faster to write the code/program, and the pre-installed modules can be used without importing them into different programs. It also doesn't add all the modules. It checks the program, and only those models are added that are used in the program again and again.

Let's see a simple code:

Code:

Output:

 
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   

Explanation:

In the above code, an error is raised because the NumPy module is not imported.

To handle the above problem, we can install the Pyforest module by typing the command

pip install pyforest

The above command installs the pyforest module for lazy import and handling of the above problem.

If you see an output like this in the command prompt, then it shows that the by forest module is installed successfully in the system.

Output:

 
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   

Let's see how to import the lazy_modules, which is provided by the pyforest model, and print all the available modules.

Code:

Output:

 
['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']   

Explanation:

In the above code, the pyforest module is imported, and all the modules are imported as the list with the help of the lazy_imports() function.

Let's see another example:

Code:

Output:

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']   

Explanation:

In the above code, an array is made with the help of a numpy module, and the array is plotted. The modules are not imported. Rather, they are called from the pyforest module.

Lazy imports are very helpful in importing the libraries automatically, which is a useful feature of the Pyforest library. If the library is not used, it is not added.