Mark Lodato Mark Lodato - 4 months ago 29
Python Question

Post import hooks in Python 3

I would like to have some callback run whenever a particular module is imported. For example (using a fake

function that does not really exist):

def set_linewidth(numpy):
import shutil

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
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.