zoukankan      html  css  js  c++  java
  • python中,reload重新加载module

    一般来说用一下代码就可reload你的module

    
    
    from importlib import reload
    reload(YourModule)

    如果你开始写的是下面的,想重新加载,

    from YourModule import *

    需要用下面几句:

    1 import YourModule # to get a module object
    2 reload(YourModule) # to reload the module
    3 from YourModule import * # to reimport all public names

    或者

    1 from importlib import reload
    2 import sys
    3 
    4 mod = reload(sys.modules['YourModule'])#use imp.reload for Python 3
    5 vars().update(mod.__dict__) #update the global namespace

    具体解释可见:

    how to reload after “from <module> import *”?

    When you do from module import * everything from that module is fetched into the current namespace and at the end the reference to module is removed. But, due to module caching the module object can still be accessed from sys.modules, so that in case you do some more import later one than it doesn't have to fetch the module again.

    That said, one way to do what you're expecting is:

    import sys
    from foo import *
    print A, B        #prints 1, 2
    A, B = 100, 200
    mod = reload(sys.modules['foo'])#use imp.reload for Python 3  
    vars().update(mod.__dict__)     #update the global namespace
    print A, B        #prints 1, 2

    As a side note, using import * is usually frowned upon:

    Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

  • 相关阅读:
    [bzoj1263]整数划分
    [bzoj3171]循环格
    [bzoj3551]Peaks加强版
    [bzoj3307]雨天的尾巴
    [bzoj2756]奇怪的游戏
    [bzoj4025]二分图
    人比人该死啊
    数据挖掘十大经典算法[0]-K-Means算法
    ISODATA算法
    CodeForces Round 197 Div2
  • 原文地址:https://www.cnblogs.com/andy-0212/p/10069057.html
Copyright © 2011-2022 走看看