4
import utils; reload(utils)

from utils import *

Why does it need load twice? 'reload' is not a built-in function. Right?

user697911
  • 10,043
  • 25
  • 95
  • 169

2 Answers2

2

Best way to find out is to check the reload document, which says:

  1. Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time.

  2. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.

  3. The names in the module namespace are updated to point to any new or changed objects.

  4. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
1

What does 'reload' do in this case?

That depends on what utils does... For example, if importing utils has a side-effect, then that effect will take place again.


Also note that using reload in any production code is definitely something that you want to avoid. The main reason that reload exists is for interactive use ...

  • load module
  • Test it out and see a bug
  • Edit module
  • Reload module
  • Test it out
  • ...
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Why does the 'side-effect' need to take place again? – user697911 Dec 29 '16 at 18:02
  • @user697911 -- I don't have any idea why the side-effect would need to happen again :-). I don't even know if `utils` _has_ a side-effect. – mgilson Dec 29 '16 at 18:03
  • After "edit" a module, you have to run the module again, and when you run the module, the first "import utils" is executed AGAIN. Why do you need to reload(utils) to get the effect? – user697911 Dec 29 '16 at 18:16
  • @user697911 -- You needed the first import to get a reference to reload. Each import first checks to see if the module was _already_ imported. If it was, then it doesn't get imported _again_. – mgilson Dec 29 '16 at 19:41