0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah this makes so much sense, thank you. I guess it's best to run my code in a new process then. The Python imports has been a recurring issue for me especially when I'm making a small web interface using Google's Mesop along with using config managers such as yacs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.