Mark Lodato Mark Lodato - 1 year ago 124
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download