5

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • reload module? Do you mean import a module twice? – Remi Guan Sep 30 '15 at 07:32
  • Rule number one: If it is possible and you need it, think twice, then do it. Only exception might be programming the software for a nuclear bomb. Then think thrice. – HeinzKurt Sep 30 '15 at 07:38

2 Answers2

8

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:

  1. 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.

  2. 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.

Community
  • 1
  • 1
alexanderlukanin13
  • 4,577
  • 26
  • 29
5

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437