pythonmodulepython-import

How to properly reload a module in Python


This question has been asked many times, here are a few for reference:

Reimport a module while interactive

Proper way to reload a python module from the console

How to reload a module's function in Python?

From what I searched and learned, I have wrote the following but it fails to properly reload the module:

import pandas as pd

pd.get_option('display.width')  # 80

pd.set_option("display.width", 150)

del pd

import importlib

import sys

pd = importlib.reload(sys.modules['pandas'])

pd.get_option('display.width')  # 150

Solution

  • Your module (pandas) in this case is actually reloaded, but importlib.reload does not clear internal memory of module-level variables, it merely re-executes the module’s code. Now, the value of the module variables after reload depends on the way it was initialized. If you define your module m.py like

    x = 0
    try:
        y
    except NameError:
        y = 0
    

    you can see the difference in behavior:

    >>> import importlib
    >>> import m
    >>> m.x
    0
    >>> m.y
    0
    >>> m.x = 1
    >>> m.y = 1
    >>> _ = importlib.reload(m)
    >>> m.x
    0
    >>> m.y
    1