杰瑞科技汇

Python 3.6如何实现模块reload?

Of course. This is a very common point of confusion for Python developers, especially when moving between different versions.

Python 3.6如何实现模块reload?-图1
(图片来源网络,侵删)

Let's break down the situation for Python 3.6.

The Short Answer

In Python 3.6, the reload() function is not a built-in function like print() or len(). It is located in the importlib library.

To use it, you must first import it:

# The correct way to use reload() in Python 3.6
from importlib import reload
# --- Example Usage ---
# 1. You have a module, let's call it my_module.py
#    (Assume this file exists in the same directory)
# 2. You import it
import my_module
# 3. You make changes to the code in my_module.py and save it.
# 4. Now, you want to reload the module without restarting your Python interpreter.
reload(my_module)

Detailed Explanation: Why is it this way?

The History: imp vs. importlib

  • Python 2: In older versions of Python (2.x), reload() was a built-in function. However, it was part of a module called imp, which was considered the "low-level" import mechanism. The common way to use it was from imp import reload.

    Python 3.6如何实现模块reload?-图2
    (图片来源网络,侵删)
  • Python 3: As part of a major cleanup and modernization effort, the imp module was deprecated in Python 3.4 and removed entirely in Python 3.12. Its functionality was consolidated into a more powerful and consistent module called importlib.

  • Python 3.6: Since imp was already deprecated, the standard and correct way to get reload() in Python 3.6 is to import it from importlib. This was the recommended practice even before 3.6.

When and Why Would You Use reload()?

reload() is a tool for interactive development and debugging. Its primary use case is:

You are working in a Python interpreter (like an interactive shell, IPython, or a Jupyter Notebook) and you have imported a module. You realize you made a mistake in the module's code, so you edit the .py file. Instead of restarting your entire interpreter (which would lose all your variables, state, and imports), you can use reload() to update the module in memory.

Python 3.6如何实现模块reload?-图3
(图片来源网络,侵删)

Important Caveats of reload():

  1. It Updates, It Doesn't Replace: reload() re-executes the module's code and updates the objects already existing in memory. It does not create a new module object. The variable name in your current session will still point to the same module object, just with its contents refreshed.

  2. Doesn't Update References: If other parts of your code have imported objects from the module, those references will not be updated.

    # In my_module.py
    # def my_function():
    #     print("Original version")
    # --- In your interpreter ---
    import my_module
    from my_module import my_function
    my_function()  # Output: Original version
    # --- Now, you edit my_module.py ---
    # def my_function():
    #     print("Updated version")
    # --- Back in the interpreter ---
    reload(my_module)  # This reloads the module
    my_module.my_function()  # Output: "Updated version" (This works)
    my_function()  # Output: "Original version" (This is the OLD object!)

    This is the most common pitfall. The my_function variable in your main scope still holds a reference to the old function object.

  3. Stateful Modules: If your module has internal state (e.g., class variables, caches), reload() will not reset this state. It will re-run the code from the top, but existing class instances and module-level variables will retain their values unless they are explicitly re-assigned.


Example Walkthrough in Python 3.6

Let's put it all together.

Step 1: Create a module file

Create a file named config.py in your current directory.

# config.py
APP_NAME = "My Awesome App"
VERSION = "1.0"
def get_status():
    print(f"Status: {APP_NAME} is running version {VERSION}")
print("config.py module has been loaded.")

Step 2: Start a Python 3.6 interpreter

Open your terminal and run python3.6.

Step 3: Initial Import

>>> import config
config.py module has been loaded.  # This is printed on import
>>> config.get_status()
Status: My Awesome App is running version 1.0
>>> config.VERSION
'1.0'

Step 4: Edit the Module

Now, go back to your text editor and change config.py:

# config.py (UPDATED)
APP_NAME = "My Awesome App"
VERSION = "1.1"  # Changed from 1.0 to 1.1
def get_status():
    print(f"Status: {APP_NAME} is running version {VERSION}")
print("config.py module has been loaded. (This is the new version)")

Step 5: Reload the Module

If you try to call config.get_status() now, it will still use the old code. You must reload it.

>>> from importlib import reload  # The crucial import
>>> config = reload(config)
config.py module has been loaded. (This is the new version)

Note: It's good practice to re-assign the result of reload() back to the module name, although it often points to the same object. It makes the code clearer.

Step 6: Verify the Changes

Now, check if the changes are reflected.

>>> config.get_status()
Status: My Awesome App is running version 1.1  # Success!
>>> config.VERSION
'1.1' # Success!

Summary for Python 3.6

Action Command/Code
Import reload from importlib import reload
Reload a module my_module = reload(my_module)
Primary Use Case Interactive development in a REPL or notebook.
Key Limitation Does not update existing references to the module's objects.
分享:
扫描分享到社交APP
上一篇
下一篇