Python 3 中的后导入钩子 [英] Post import hooks in Python 3
问题描述
每当导入特定模块时,我都希望运行一些回调.例如(使用一个不存在的假 @imp.when_imported
函数):
@imp.when_imported('numpy')def set_linewidth(numpy):进口商铺numpy.set_printoptions(linewidth=shutil.get_terminal_size()[0])
此功能是在 PEP 369: Post import hooks 中设计的,但是被撤回的原因:
<块引用>此 PEP 已被作者撤回,因为在迁移到 Python 3.3 中的 importlib 后,许多详细设计不再有效.
但是 importlib 没有明确的解决方案.如何使用 importlib
来实现一个 post-import 钩子?
wrapt
模块提供了一个实现.
观看有关 wrapt
的视频,包括此功能:
不要认为 wrapt
的文档还没有提到它.
部分博客文章末尾:
尽管说.
wrapt
有一个名为 autowrapt
的配套模块,它允许您使用这种机制进行猴子修补,而无需更改应用程序代码本身来触发它.>
I would like to have some callback run whenever a particular module is imported. For example (using a fake @imp.when_imported
function that does not really exist):
@imp.when_imported('numpy')
def set_linewidth(numpy):
import shutil
numpy.set_printoptions(linewidth=shutil.get_terminal_size()[0])
This feature was designed in PEP 369: Post import hooks but was withdrawn with the reason:
This PEP has been withdrawn by its author, as much of the detailed design is no longer valid following the migration to importlib in Python 3.3.
But importlib has no clear solution. How does one use importlib
to implement a post-import hook?
The wrapt
module provides an implementation of this.
Watch this video about wrapt
, including this feature:
Don't think the documentation for wrapt
mentions it yet.
Some of the blogs posts at end of:
talk about it though.
There is a companion module for wrapt
called autowrapt
which allows you to do monkey patching using this mechanism without needing to change the application code itself to trigger it.
这篇关于Python 3 中的后导入钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!