眾所周知,Python 應(yīng)用程序在執(zhí)行用戶的實際操作之前,會執(zhí)行 import 操作,不同的模塊可能來自不同的位置,某些模塊的運行可能非常耗時,某些模塊可能根本不會被用戶調(diào)用,因此很多模塊的導(dǎo)入純粹是浪費時間。
如果你的 Python 程序程序有大量的 import,而且啟動非常慢,那么你應(yīng)該嘗試懶導(dǎo)入,本文分享一種實現(xiàn)惰性導(dǎo)入的一種方法。雖然 PEP0690[1] 已經(jīng)提案讓 Python 編譯器(-L) 或者標(biāo)準(zhǔn)庫加入這個功能,但目前的 Python 版本還未實現(xiàn)。
眾所周知,Python 應(yīng)用程序在執(zhí)行用戶的實際操作之前,會執(zhí)行 import 操作,不同的模塊可能來自不同的位置,某些模塊的運行可能非常耗時,某些模塊可能根本不會被用戶調(diào)用,因此很多模塊的導(dǎo)入純粹是浪費時間。
因此我們需要惰性導(dǎo)入,當(dāng)應(yīng)用惰性導(dǎo)入時,運行 import foo 僅僅會把名字 foo 添加到全局的全名空間(globals())中作為一個懶引用(lazy reference),編譯器遇到任何訪問 foo 的代碼時才會執(zhí)行真正的 import 操作。類似的,from foo import bar 會把 bar 添加到命名空間,當(dāng)遇到調(diào)用 bar 的代碼時,就把 foo 導(dǎo)入。
寫代碼實現(xiàn)
那怎么寫代碼實現(xiàn)呢?其實不必寫代碼實現(xiàn),已經(jīng)有項目實現(xiàn)了懶導(dǎo)入功能,那就是 TensorFlow,它的代碼并沒有任何三方庫依賴,我把它放到這里,以后大家需要懶導(dǎo)入的時候直接把 LazyLoader[2] 類復(fù)制到自己的項目中去即可。
源代碼如下:
# Code copied from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py
"""A LazyLoader class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import importlib
import types
class LazyLoader(types.ModuleType):
"""Lazily import a module, mainly to avoid pulling in large dependencies.
`contrib`, and `ffmpeg` are examples of modules that are large and not always
needed, and this allows them to only be loaded when they are used.
"""
# The lint error here is incorrect.
def __init__(self, local_name, parent_module_globals, name): # pylint: disable=super-on-old-class
self._local_name = local_name
self._parent_module_globals = parent_module_globals
super(LazyLoader, self).__init__(name)
def _load(self):
# Import the target module and insert it into the parent's namespace
module = importlib.import_module(self.__name__)
self._parent_module_globals[self._local_name] = module
# Update this object's dict so that if someone keeps a reference to the
# LazyLoader, lookups are efficient (__getattr__ is only called on lookups
# that fail).
self.__dict__.update(module.__dict__)
return module
def __getattr__(self, item):
module = self._load()
return getattr(module, item)
def __dir__(self):
module = self._load()
return dir(module)
代碼說明:
類 LazyLoader 繼承自 types.ModuleType,初始化函數(shù)確保惰性模塊將像真正的模塊一樣正確添加到全局變量中,只要真正用到模塊的時候,也就是執(zhí)行 __getattr__ 或 __dir__ 時,才會真正的 import 實際模塊,更新全局變量以指向?qū)嶋H模塊,并且將其所有狀態(tài)(__dict__)更新為實際模塊的狀態(tài),以便對延遲加載的引用,加載模塊不需要每次訪問都經(jīng)過加載過程。
代碼使用:
正常情況下我們這樣導(dǎo)入模塊:
import tensorflow.contrib as contrib
其對應(yīng)的惰性導(dǎo)入版本如下:
contrib = LazyLoader('contrib', globals(), 'tensorflow.contrib')
PEP0690 建議的做法
PEP0690 的提案是在編譯器( C 代碼)層面實現(xiàn),這樣性能會更好。其使用方法有兩種。
其一
一種方式是執(zhí)行 Python 腳本時加入 -L 參數(shù),比如有兩個文件 spam.py 內(nèi)容如下:
import time
time.sleep(10)
print("spam loaded")
egg.py 內(nèi)容如下:
import spam
print("imports done")
正常導(dǎo)入情況下,會等 10 秒后先打印 "spam loaded",然后打印 "imports done",當(dāng)執(zhí)行 python -L eggs.py 時,spam 模塊永遠(yuǎn)不會導(dǎo)入,應(yīng)用 spam 模塊壓根就沒有用到。如果 egg.py 內(nèi)容如下:
import spam
print("imports done")
spam
當(dāng)執(zhí)行 python -L eggs.py 時會先打印 "imports done",10 秒之后打印 "spam loaded")。
其二
另一種方式是調(diào)用標(biāo)準(zhǔn)庫 importlib 的方法:
import importlib
importlib.set_lazy_imports(True)
如果某些模塊不能懶加載,需要排除,可以這樣
import importlib
importlib.set_lazy_imports(True,excluding=["one.mod", "another"])
還可以這樣:
from importlib import eager_imports
with eager_imports():
import foo
import bar
最后的話
經(jīng)過專業(yè)人士在真實的 Python 命令行程序上做測試,應(yīng)用惰性導(dǎo)入后,可以使啟動時間提高 70%,內(nèi)存使用減少 40%,非??捎^了。
參考資料
[1]PEP0690: https://github.com/python/peps/blob/main/pep-0690.rst
[2]LazyLoader: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/lazy_loader.py