Python REPL中的模块导入机制
- How does importing in Python work?
Turns out that, for efficiency reasons, when you import a module in an interactive Python session, Python interpreter does two steps:
-
First, it checks if the module is already cached in the sys.module
dictionary. -
And only if it’s not there, it actually imports the
module
Another one of the magic methods in IPython is related to reloading modules. It’s called %autoreload. It’s not enabled by default, so you have to load it as an extension:
%autoreload 0 - disables the auto-reloading. This is the default setting.
%autoreload 1 - it will only auto-reload modules that were imported using the %aimport function (e.g %aimport my_module). It’s a good option if you want to specifically auto-reload only a selected module.
%autoreload 2 - auto-reload all the modules. Great way to make writing and testing your modules much easier.