Python — Globally Override Function Imports

To globally override imports (per python session), modify sys.modules to whatever you’d like.

import sys

sys.modules['csv'] = 'I just replaced the csv module'

import csv
print csv  # output 'I just replaced the csv module'

That’s pretty straight forward, but if you need to replace a function within a module, you’d have to pull out the module, set the new function, and set the module in sys.modules.


import sys

module = sys.modules['module']
module.myfunction = lambda: 'my new function'

sys.modules['module'] = module

from module import myfunction
myfunction() # output 'my new function'
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s