In "Modules and Packages: Live and Let Die!", page 28 (see also the video), it's said that:
You can force-reload a module, but you're never supposed to do it.
Can anyone explain why we are not supposed to reload modules in Python?
In "Modules and Packages: Live and Let Die!", page 28 (see also the video), it's said that:
You can force-reload a module, but you're never supposed to do it.
Can anyone explain why we are not supposed to reload modules in Python?
Reloading is explained in detail here: How do I unload (reload) a Python module?
tl;rd
There are some valid use cases for reload
, like Django development server. But in general, reloading modules has too many caveats to be practical.
Two largest concerns are:
To completely unload old objects, you must make sure that no other module or object keeps references to them (which is generally impossible). If you fail here, you may get a hard-to-trace memory leak or an unexpected behavior.
There is no general way to reload a module with C extensions. Some may reload safely; some may seem to reload safely, but leak, and some may crash your interpreter or produce weird bugs.
Reloading a module is something you would generally do during development, so you can continue running the same interpreter session but get the changes you've made to the module in it. This is actually explained in the video, with an example, from about 11 minutes in.
However, if you find yourself writing actual functionality that relies on modules changing and being reloaded at run time, you should make very sure that you know what you're doing and have considered other options first.