In this lesson, you’ll learn about reloading a module. For efficiency, a module is only loaded once per interpreter session. That’s fine for function and class definitions, which typically make up the bulk of a module’s contents.
But a module can contain executable statements as well, usually for initialization. Be aware that these statements will only be executed the first time a module is imported.
Take a look at mod.py
:
s = "Computers are useless. They can only give you answers."
a = [100, 200, 300]
def printy(arg):
print(f'arg = {arg}')
class Classy:
pass
print(f'a = {a}')
Here’s what you get:
>>> import mod
a = [100, 200, 300]
>>> import mod
>>> import mod
>>> mod.a
[100, 200, 300]
>>> mod.s
'Computers are useless. They can only give you answers.'
The print()
statement is not executed on subsequent imports. (For that matter, neither is the assignment statement, but as the final display of the value of mod.a
shows, that doesn’t matter. Once the assignment is made, it sticks.)
If you make a change to a module and need to reload it, you need to either restart the interpreter or use a function called reload()
from module importlib
. Without exiting the REPL, change mod.py
:
s = "Computers are useless. They can only give you answers."
a = [100, 200, 300]
def printy(arg):
print(f'arg = {arg}')
class Classy:
pass
print(f'a is equal {a}')
Now import mod
again:
>>> import mod
>>> exit()
Nothing happens, and the changes to the file are not shown. Exit the REPL and then enter it again:
>>> import mod
a is equal [100, 200, 300]
>>> import mod
>>> import importlib
>>> importlib.reload(mod)
a is equal [100, 200, 300]
<module 'mod' from '/Users/chris/ModulesAndPackages/mod.py'>
J on May 16, 2020
Ok, and the usefulness is how? I am not seeing the use case for this and why it is useful to know about it?