新聞中心
如果你的 Python 程序程序有大量的 import,而且啟動(dòng)非常慢,那么你應(yīng)該嘗試懶導(dǎo)入,本文分享一種實(shí)現(xiàn)惰性導(dǎo)入的一種方法。雖然 PEP0690[1] 已經(jīng)提案讓 Python 編譯器(-L) 或者標(biāo)準(zhǔn)庫(kù)加入這個(gè)功能,但目前的 Python 版本還未實(shí)現(xiàn)。

眾所周知,Python 應(yīng)用程序在執(zhí)行用戶(hù)的實(shí)際操作之前,會(huì)執(zhí)行 import 操作,不同的模塊可能來(lái)自不同的位置,某些模塊的運(yùn)行可能非常耗時(shí),某些模塊可能根本不會(huì)被用戶(hù)調(diào)用,因此很多模塊的導(dǎo)入純粹是浪費(fèi)時(shí)間。
因此我們需要惰性導(dǎo)入,當(dāng)應(yīng)用惰性導(dǎo)入時(shí),運(yùn)行 import foo 僅僅會(huì)把名字 foo 添加到全局的全名空間(globals())中作為一個(gè)懶引用(lazy reference),編譯器遇到任何訪問(wèn) foo 的代碼時(shí)才會(huì)執(zhí)行真正的 import 操作。類(lèi)似的,from foo import bar 會(huì)把 bar 添加到命名空間,當(dāng)遇到調(diào)用 bar 的代碼時(shí),就把 foo 導(dǎo)入。
寫(xiě)代碼實(shí)現(xiàn)
那怎么寫(xiě)代碼實(shí)現(xiàn)呢?其實(shí)不必寫(xiě)代碼實(shí)現(xiàn),已經(jīng)有項(xiàng)目實(shí)現(xiàn)了懶導(dǎo)入功能,那就是 TensorFlow,它的代碼并沒(méi)有任何三方庫(kù)依賴(lài),我把它放到這里,以后大家需要懶導(dǎo)入的時(shí)候直接把 LazyLoader[2] 類(lèi)復(fù)制到自己的項(xiàng)目中去即可。
源代碼如下:
# 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)
代碼說(shuō)明:
類(lèi) LazyLoader 繼承自 types.ModuleType,初始化函數(shù)確保惰性模塊將像真正的模塊一樣正確添加到全局變量中,只要真正用到模塊的時(shí)候,也就是執(zhí)行 __getattr__ 或 __dir__ 時(shí),才會(huì)真正的 import 實(shí)際模塊,更新全局變量以指向?qū)嶋H模塊,并且將其所有狀態(tài)(__dict__)更新為實(shí)際模塊的狀態(tài),以便對(duì)延遲加載的引用,加載模塊不需要每次訪問(wèn)都經(jīng)過(guò)加載過(guò)程。
代碼使用:
正常情況下我們這樣導(dǎo)入模塊:
import tensorflow.contrib as contrib
其對(duì)應(yīng)的惰性導(dǎo)入版本如下:
contrib = LazyLoader('contrib', globals(), 'tensorflow.contrib')
PEP0690 建議的做法
PEP0690 的提案是在編譯器( C 代碼)層面實(shí)現(xiàn),這樣性能會(huì)更好。其使用方法有兩種。
其一
一種方式是執(zhí)行 Python 腳本時(shí)加入 -L 參數(shù),比如有兩個(gè)文件 spam.py 內(nèi)容如下:
import time
time.sleep(10)
print("spam loaded")
egg.py 內(nèi)容如下:
import spam
print("imports done")
正常導(dǎo)入情況下,會(huì)等 10 秒后先打印 "spam loaded",然后打印 "imports done",當(dāng)執(zhí)行 python -L eggs.py 時(shí),spam 模塊永遠(yuǎn)不會(huì)導(dǎo)入,應(yīng)用 spam 模塊壓根就沒(méi)有用到。如果 egg.py 內(nèi)容如下:
import spam
print("imports done")
spam
當(dāng)執(zhí)行 python -L eggs.py 時(shí)會(huì)先打印 "imports done",10 秒之后打印 "spam loaded")。
其二
另一種方式是調(diào)用標(biāo)準(zhǔn)庫(kù) 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
最后的話(huà)
經(jīng)過(guò)專(zhuān)業(yè)人士在真實(shí)的 Python 命令行程序上做測(cè)試,應(yīng)用惰性導(dǎo)入后,可以使啟動(dòng)時(shí)間提高 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
新聞標(biāo)題:如何實(shí)現(xiàn)Python的惰性導(dǎo)入-lazyimport
文章轉(zhuǎn)載:http://fisionsoft.com.cn/article/cdicpes.html


咨詢(xún)
建站咨詢(xún)
