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?
When you import a module, the Python interpreter searches for the module in the following sequences: The current directory. If the module isn't found in the current directory, Python searches each directory in the shell variable PYTHONPATH. If the current directory and PYTHONPATH fail, Python checks the default path.
A Python module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use.
A Python Module can be a simple python File (. py extension file), i.e., a combination of numerous Functions and Global variables. A Python Package is a collection of different Python modules with an __init__.py File. __init__.py Python File works as a Constructor for the Python Package.
What are modules in Python? Modules refer to a file containing Python statements and definitions. A file containing Python code, for example: example.py , is called a module, and its module name would be example . We use modules to break down large programs into small manageable and organized files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With