Jan 13, 2014

Reload and unload modules in Python

# python 2.7
import math

reload(math) # or import math again to reload the module
del(math) # unload module

# python 3.x
import math

# the reload function was eliminated on python 3
import math # or use exec("import math")
del(math) # remove module

2 comments:

  1. >>> import hello
    >>> sys.getrefcount(hello)
    3

    Probably want to del the other reference as well, which is sys.modules["hello"].

    Else gc won't be able to release the resources of the module :)

    ReplyDelete