Reimport a module in python while interactive

前端 未结 6 1295
后悔当初
后悔当初 2020-11-27 08:45

I know it can be done, but I never remember how.

How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker wit

6条回答
  •  借酒劲吻你
    2020-11-27 09:27

    Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

    If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

    However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

    # Python >= 3.5
    import importlib
    import types
    
    
    def walk_reload(module: types.ModuleType) -> None:
        if hasattr(module, "__all__"):
            for submodule_name in module.__all__:
                walk_reload(getattr(module, submodule_name))
        importlib.reload(module)
    
    
    walk_reload(my_module)
    

    The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

提交回复
热议问题