Python reload module

Author : xuzhiping   2022-11-09 15:43:55 Browse: 1229
Category : Python

Abstract: Brief introduction In modular programming, we often encounter such a scenario: Write a Python module and use the import my_module...

Brief introduction

In modular programming, we often encounter such a scenario:

Write a Python module and use the import my_module to import in the form of When changes are made to the module, any changes will not be recognized even if they are re-imported This makes module debugging very difficult.

So, how to solve this problem?

Write a Python module and import it as import my_module. When changes are made to the module, any changes in it will not be recognized even if they are re-imported, which makes module debugging very difficult.

python

Modules are imported only once

For efficiency reasons (the import must find the file, compile it into bytecode, and run the code), the Python shell imports each module only once per session. For example, there is a module named hello.py that contains the following code:

Print ('Hello, Python')

What happens if you import it multiple times?

>>> import hello
Hello, Python!
>>>
>>> import hello
>>> import hello

As you can see, the code was executed only once. That is, the module was imported only once.

Reload module

If you change a module that has already been imported in the Python shell and then re-import the module, Python will think "I have already imported the module and do not need to read the file again", so the change will be invalid.

There are several ways to solve this problem:

  • The easiest and most effective way: restart the Python shell. However, this also has drawbacks, especially the loss of data that exists in the Python shell namespace and data from other imported modules.
  • For simple cases, you can use Python's reload() function. In many cases, it is enough after editing a module.
  • For more complex cases, reloading the edited module also requires reloading its dependent/imported modules (since they must be initialized as part of the initialization of the edited module), so IPython's autoreload extension is useful.

PS: The second way is mainly introduced below - reload(), other ways to try on your own.

reload() is a concise way provided by Python that behaves differently in different versions of Python:

  • In Python 2.x, reload () is a built-in function.
  • In Python 3.03.3, you can use imp.reload (module).
  • In Python 3. 4, imp has been abandoned and replaced by importlib.
    >>> import importlib
    >>> import hello
    Hello, Python! # content before modification
    >>>
    >>> importlib.reload (hello)
    I am coming... # modified content
    <module 'hello' from '/home/wang/Projects/hello.py'>
Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).