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'

1 Comment

  1. Sanjay Kumar says:

    other way is :
    import module
    module.function = lambda : myfunction()

Leave a Comment