reloading module which has been imported to another module

后端 未结 6 1059
难免孤独
难免孤独 2021-01-01 19:32

Let\'s face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling import at the in

6条回答
  •  悲哀的现实
    2021-01-01 20:03

    To reload a module, you have to use reload, and you have to use it on the module you want to reload. Reloading a module doesn't recursively reload all modules imported by that module. It just reloads that one module.

    When a module is imported, a reference to it is stored, and later imports of that module re-use the already-imported, already-stored version. When you reload module1, it re-runs the from module2 import ... statement, but that just reuses the already-imported version of module2 without reloading it.

    The only way to fix this is to change your code so it does import module2 instead of (or in addition to) from module2 import .... You cannot reload a module unless the module itself has been imported and bound to a name (i.e., with an import module statement, not just a from module import stuff statement).

    Note that you can use both forms of the import, and reloading the imported module will affect subsequent from imports. That is, you can do this:

    >>> import module
    >>> from module import x
    >>> x
    2
    # Change module code here, changing x to 3
    >>> reload(module)
    >>> from module import x
    >>> x
    3
    

    This can be handy for interactive work, since it lets you use short, unprefixed names to refer to what you need, while still being able to reload the module.

提交回复
热议问题