how to reload a Class in python shell?

后端 未结 6 1864
既然无缘
既然无缘 2020-12-07 10:47

If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the __init__.py of the parent package. See

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 10:54

    I finally found the answer:

    import MyPak
    from MyPak import MyMod
    

    after editing MyPak/MyMod.py file, to reload the class MyMod in the file MyMod.py, one needs to

    import sys
    del sys.modules['MyPak.MyMod'] 
    reload(MyPak)
    from MyPak import MyMod
    

    Caveats:

    1. Executing del MyPak or del MyMod or del MyPak.MyMod does not solve the problem since it simply removes the name binding. Python only searches sys.modules to see whether the modules had already been imported. Check out the discussion in the post module name in sys.modules and globals().

    2. When reloading MyPak, python tries to execute the line from MyMod import MyMod in MyPak/__init__.py. However, it finds MyPak.MyMod in sys.modules, thus it will NOT reload MyMod although MyPak/MyMod.py has been updated. And you will find that no new MyPak/MyMod.pyc is generated.

提交回复
热议问题