0

I want to make changes to a file, and I want it to reflect in real-time without restarting my program and losing all the memory states.

Suppose I imported a function like this:

from A.B.C.foo import bar

There are multiple imports like this in multiple files.

How do I reload all of them? (Or say, just one)

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
Anonymous Guy
  • 119
  • 2
  • 11
  • 1
    `importlib.reload(sys.modules['module_name'])` – alex_noname Jun 27 '20 at 08:57
  • So is it `reload(sys.modules['A.B.C.foo'])`? Or `reload(sys.modules['A.B.C.foo.bar'])`? Or `reload(sys.modules['bar'])`? And how do I go about filtering local files from sys.modules to avoid explicitly mentioning everytime? – Anonymous Guy Jun 27 '20 at 09:05

2 Answers2

0

To reload one module: In older versions of Python there was a builtin reload() method. It's been moved to the importlib module, but for awhile it also lived in the imp module.

In [1]: import pandas

In [2]: from importlib import reload

In [3]: reload(pandas)

To reload a bunch: If you know which modules you want to reload, you can of course just call reload() as much as you need. To detect all of the modules which have been imported is actually a bit tricky though. A limited version which will get all modules imported by saying import mod is:

import sys
modulenames = set(sys.modules) & set(globals())
allmodules = [sys.modules[name] for name in modulenames]
Frank
  • 459
  • 2
  • 9
0

To reload function:

import sys, importlib
importlib.reload(sys.modules['A.B.C.foo'])
from A.B.C.foo import bar
alex_noname
  • 26,459
  • 5
  • 69
  • 86