Reloading Modules
2 min read ยท
What Happens When a Module is Imported Multiple Times
When a module is imported for the first time, Python:
- Loads the module
- Executes all top level code
- Stores it in memory
If you import the same module again, Python does not execute it again.
It uses the already loaded version from memory.
๐ The module runs only once.
Note
Python caches imported modules in memory to improve performance.
Problem Scenario
If you modify the module after importing it, changes will not reflect automatically.
importlib.reload()
To reload a module and apply latest changes, use
importlib.reload().Caution
Reloading modules frequently can lead to unexpected behavior, especially in large applications.
Module Attributes and Functions
Python provides built in functions and attributes to explore modules.
dir()
Returns a list of all attributes and functions inside a module.
help()
Displays detailed documentation about a module or function.
Pro Tip
Use help() to understand how a function works without checking external documentation.
file
Shows the file path of the module.
name
Tells how the module is being used.
- Built-in modules โ module name
- Custom modules โ module name or main
Understanding Behavior Together
Real World Scenario
Developers use dir() and help() to explore unfamiliar libraries and understand available functions quickly.
Exercise
- Import any module
- Use dir() to list its functions
- Use help() on one function
- Print file and name values