Mark Lodato Mark Lodato - 18 days ago 6
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

@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?

Answer

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.

Comments