Explain Codes LogoExplain Codes Logo

Reimport a module while interactive

python
importlib
reload
ipython
Alex KataevbyAlex Kataev·Aug 24, 2024
TLDR

Need an instant refresh of your Python module? Use importlib.reload(). If you have made changes to some_module and need to update it within a live session, you can do so as follows:

import some_module from importlib import reload reload(some_module) # Voila! You've got the updated module now.

This piece of code works as a real-time update, syncing some_module with the latest edits.

The 411 about reload()

Syncing Module Changes

If you're a proud Pythonista tweaking your module's source code but wondering why the changes are not reflecting in the interactive session — importlib.reload() is your buddy. It updates the module with the latest changes.

# After your ninja edits to 'my_module.py' import importlib.reload reload(my_module) # There you go!

Preserving Original Objects

Your existing objects from the module before the reload will stick around with their state and identity intact. So, if you've got an instance named my_instance of my_module.MyClass, it will still be there after the reload, albeit linked to the old class definition.

my_instance = my_module.MyClass() # Created a MyClass instance reload(my_module) # 'my_instance' says, "Why you reload without me?"

Imports: Direct vs. From

To effectively use the reload, stick with direct imports (e.g., import my_module) instead of from my_module import .... When you use direct imports, the reloaded module's namespace is updated. However, with the latter syntax, the loaded symbols might not reflect the updates.

Alias: A matter of identity

If you've got an alias for your module during import (like how pythonistas prefer their Starbuck names), ensure to use the same alias during reload:

import my_module as mm # my_module alias mm checks-in reload(mm) # mm says, "Hey, I'm mm, not my_module. Remember me?"

Handy Tips and Tricks for Real Pythonistas

Automagic Reloading with IPython

IPython's autoreload extension can auto-refresh your module, allowing you to keep the development flowing without manual reloads:

%load_ext autoreload %autoreload 2 # With this, Python plays by the "change is constant" rule.

Deprecated imp — A Tale of Forgotten Relic

Once upon a time in Python 3.2 and 3.3, imp.reload() was a thing. Now, it's a deprecated tech relic. Today's hip method is importlib.reload().

Version-specific Plot Twist

In the Python cinematic universe, reload() was a built-in function in Python 2.x. However, in Python 3.x, reload() lost its built-in status. Now, it bravely lives on as importlib.reload().

Seamless Workflow

Maintain the continuity of your workflow by using importlib.reload() to update your modules without needing a session restart. It reflects .py file edits instantly, allowing you to focus on coding without disruptions.