Skip to content Skip to sidebar Skip to footer

Re-import The Same Python Module With __import__() In A Fail-safe Way

I'm using __import__ to import a python module. However I'd like to implement a solution to re-import a module which may changed meanwhile (developing/debugging purposes). If I try

Solution 1:

The right way to reimport a module is with reload, however you're correct that you'd want to protect against failure in the reimport. I'd suggest taking a look at superreload from the IPython autoreload extension (source).

This should deal with errors in the reload:

old_dict = module.__dict__.copy()
try:module = reload(module)
except:module.__dict__.update(old_dict)
    raise

Post a Comment for "Re-import The Same Python Module With __import__() In A Fail-safe Way"